AI Run Lab

All chapters

Pretraining from scratch

A language model can learn without an existing LLM. A small causal Transformer and a few lines of artificial text are enough to see how the training signal is produced.

Open this chapter with experiments and audio

Where do the correct answers come from?

For next-token training, each token in an observed text supplies the target for the preceding position. In the toy sequence A B C A, the input is A B C and the targets are B C A. The model at the first position sees A. At the second it sees A B. A causal mask enforces these information boundaries, even when all positions are evaluated together.

PositionAvailable prefixTarget
0AB
1A BC
2A B CA

The model produces a probability distribution at each position. Cross-entropy loss for a single observed token is the negative natural logarithm of its probability. Predicting the right token with probability 0.5 costs about 0.693. Raising that probability to 0.9 reduces the loss to about 0.105. Training averages this signal over many positions.

Choose B as the observed target and raise its score. Then change only the observed target to A. Watch what happens to the loss.

If all three scores are equal, each token gets probability one third and the loss is ln(3), about 1.099. Giving B a high score helps on positions whose observed target is B. It costs more loss on positions where a different token actually follows.

How do we make a miniature GPT-style model?

The program below uses three token IDs, eight context positions, 16 features per position and one Transformer layer. Its small size keeps the experiment practical on a CPU. Install PyTorch in a local Python environment, save the code as tiny_lm.py and run python tiny_lm.py. Its entire dataset is generated in the script. No checkpoint or external text is needed.

import torch
from torch import nn
from torch.nn import functional as F

torch.set_num_threads(1)
torch.manual_seed(7)
context = 8
text = "abc" * 100
ids = torch.tensor(["abc".index(ch) for ch in text])

class TinyLM(nn.Module):
    def __init__(self):
        super().__init__()
        self.token = nn.Embedding(3, 16)
        self.pos = nn.Embedding(context, 16)
        self.block = nn.TransformerEncoderLayer(
            16, 2, dim_feedforward=32, dropout=0, batch_first=True)
        self.head = nn.Linear(16, 3)

    def forward(self, x):
        length = x.size(1)
        positions = torch.arange(length, device=x.device)
        mask = torch.ones(length, length, dtype=torch.bool,
                          device=x.device).triu(1)
        h = self.token(x) + self.pos(positions)
        return self.head(self.block(h, src_mask=mask))

model = TinyLM()
opt = torch.optim.AdamW(model.parameters(), lr=0.01)
for step in range(80):
    start = torch.randint(len(ids) - context, (8, 1))
    i = start + torch.arange(context)
    scores = model(ids[i])
    loss = F.cross_entropy(scores.reshape(-1, 3), ids[i+1].reshape(-1))
    opt.zero_grad()
    loss.backward()
    opt.step()
    if step in (0, 79):
        print(step, round(loss.item(), 4))

torch.save(model.state_dict(), "tiny_lm.pt")
restored = TinyLM()
restored.load_state_dict(torch.load("tiny_lm.pt", weights_only=True))
restored.eval()
sequence = [0]
with torch.no_grad():
    for _ in range(12):
        x = torch.tensor([sequence[-context:]])
        sequence.append(restored(x)[0, -1].argmax().item())
print("".join("abc"[i] for i in sequence))

What do the printed results mean?

The input and target arrays have identical shapes but point to adjacent tokens. The model returns one score per vocabulary entry for every input position. The loss combines those scores with the target IDs. PyTorch differentiates the loss, then AdamW updates the randomly initialized weights. In generation, the code chooses the highest-scoring next ID, appends it and repeats.

You should see loss fall and a continuation such as “abcabcabcabca”. The final lines use the weights reloaded from disk. PyTorch calls the reusable module an encoder layer. Here its mask permits only preceding and current positions, giving this block causal decoder-style behaviour. Try removing the position embeddings. This toy pattern can be predicted almost entirely from the final character, so it is a weak test of order learning.

What changes when the dataset contains real language?

Many continuations of a real sentence are plausible. Training rewards probability on observed tokens across many contexts. A model may reduce its loss by learning spelling, syntax and regularities that support factual or mathematical answers. Duplicated documents can overrepresent a pattern and leak across a train–test split. Split by document before extracting nearby windows. Evaluate on separate text and tasks you care about.

Does a low loss on the artificial cycle establish general language understanding?

No. A three-entry lookup of the next character could solve the task. Evaluate harder patterns and held-out examples to find out what your model learned.

Source · PyTorch · TransformerEncoderLayer

Follow four predictions back to one update

For a training fragment with five tokens there are four ordinary next-token targets. At each position the decoder sees the prefix and assigns a probability to the actual next ID. Suppose those probabilities are 0.5, 0.25, 0.5 and 1. Taking minus the natural logarithm gives losses of about 0.69, 1.39, 0.69 and 0. Their mean is about 0.69. The target with probability 0.25 makes the largest contribution.

Backpropagation finds how a small change in each weight would change the batch loss. An optimizer uses these gradients to update the weights. One embedding row can also affect contexts other than the training fragment because every occurrence of that token uses it. The output projection and the repeated block weights are shared too. This sharing creates both transfer to new contexts and interference with older ones.

Change the probability assigned to the observed token →

Sources · Brown et al., 2020

Who decides which mistakes dominate the batch?

Suppose 900 of 1,000 sampled target tokens come from English manuals and 100 from Dutch support chats. With equal weight per token, average losses of 1 and 3 yield a combined loss of 1.2. If the mix becomes 500 and 500, exactly the same model scores 2. The monitoring graph can jump even when every prediction stays the same. Keep a fixed validation mixture and report both components.

The Academy’s room decoder saw examples containing eight metres but never the pair eight by eight during training. The token 64 exists in the vocabulary, so the model can represent the right answer. That held-out case probes a new combination. For a manual-writing model, two translated editions of the same manual could leak the answer across a random document split. Group editions by source before choosing the split. State the kind of generalization each test actually measures.

Compare a training question with the held-out arithmetic case →