Training Your First Model: A Mini LLM on Tiny Shakespeare
Setup and data
Goal: train a small model on Tiny Shakespeare so it writes text with a Shakespeare-like structure (speaker, lines, reply).
- Device check -> torch.cuda.is_available() (CUDA = NVIDIA GPU)
- Macbook -> use MPS instead of CUDA
- No GPU -> CPU, very slow
- Colab T4 GPU is enough; Colab Pro not needed
Vocabulary - all tokens the model has access to. Each token gets an ID, and the ID looks up its embedding.
- Character-level tokenization: every character is a token
- Take the set of text (unique characters), then sort
- Two dictionaries: char -> ID (encode) and ID -> char (decode)
- Vocab size = 65 (capitals, small letters, punctuation)
- Data is already clean, so no cleaning step
Assignment: implement Byte Pair Encoding (BPE) yourself instead of character tokens.
Train/validation split
Keep part of the data unseen during training. It tells us whether the model does well on new data.
- 90% training, 10% validation
- Split ratio depends on data size; big data can use more for validation
Batches and next-token targets
Autoregressive models learn by next-token prediction. So the target is the input shifted by one.
Example
X = chars at i..i+n, Y = chars at i+1..i+n+1. For input 'T' the target is 'H'; for 'H' it is 'E'.
- Each run picks a different random sequence
- Because tokens are characters, this is next-character prediction
RMSNorm in code
- LayerNorm needed mean, std, scale and shift; RMSNorm only RMS and scale
- eps = 1e-6 default (avoids divide by zero)
- weight -> learnable parameter, initialised to ones, size = model dimension
- Forward: square, mean, root, divide input by RMS, multiply by weight
Dropout
The Problem: with many parameters the model may memorise the data instead of generalising (overfitting).
The Solution: Dropout - randomly set a fraction of values in a layer to zero.
- Dropout 0.2 -> 20% of values zeroed, e.g. 2 of 10 neurons
- Chosen at random every step
- Model cannot rely on any single feature
- Used only in training; turned off when predicting after training
- Value 0.2 is a common choice from papers; applied in most layers
RoPE in code
- Step 1: precompute frequency per pair, then cos and sin tables by position
- Low dimensions -> high frequency, fast rotation (short-range patterns)
- High dimensions -> low frequency, slow rotation (long-range patterns)
- Step 2: split into x1 (even dims) and x2 (odd dims), rotate each pair
- After rotation, Q·K depends only on relative position
RoPE is not applied to V. Value holds the token's actual information, which should not change with position. Only Q and K decide similarity.
- flatten -> turns a tensor into one dimension, e.g. 3x3 to a single 9-element vector
- Learn PyTorch functions by reading the PyTorch docs examples
GQA in code
- Config: 8 query heads, 2 KV heads, so each KV pair serves 4 queries
- Forward: project Q, K, V -> reshape -> apply RoPE to Q and K -> repeat KV heads -> softmax(QK^T/sqrt(d)) V -> dropout
- expand -> repeats KV heads by editing metadata only, memory efficient, no new copy
- Causal mask: torch.triu sets everything above the diagonal to -infinity
SwiGLU in code
def forward(self, x):
gate = F.silu(self.w_gate(x))
up = self.w_up(x)
return self.dropout(self.w_down(gate * up))F -> torch.nn.functional, the library holding relu, silu and similar operations.
Transformer block and full LM
Residual connection - add the previous input back so information is not lost and gradients do not shrink.
Full LM: token embeddings -> N transformer blocks -> final RMSNorm -> linear head -> logits.
| Setting | Value |
|---|---|
| Vocab size | 65 |
| Model dim | 256 |
| Layers | 4 |
| Query heads | 8 |
| KV heads | 2 |
| FFN dim | 680 |
| Sequence length | 256 |
| Parameters | about 3 million |
.to(device) moves the model to the GPU.
Training run
Hyperparameters - settings humans choose (steps, batch size, learning rate, eval interval). The model does not learn them.
- Per step: get batch -> forward (logits, loss) -> optimizer.zero_grad() -> loss.backward() -> optimizer.step()
- torch.no_grad() -> no gradients tracked; used for loss estimation since no backprop needed
- Evaluate on train and validation splits every 250 steps
- Training loss started near 4.2 and fell steadily
If validation loss falls then rises while train loss keeps falling, the model overfits. Fix: remove parameters or layers, add dropout.
Generation and temperature
Generate: encode prompt -> logits -> divide by temperature -> softmax -> sample next token -> append -> repeat.
- Temperature is a hyperparameter set at generation
- T near 0 -> always the top token (deterministic, conservative)
- Higher T -> lower-probability tokens get chosen (creative, varied)
- Prompt 'Romeo': T=0.5 gave coherent speaker-reply structure; T=1.2 gave noisy text
- Coding use often around 0.3 to 0.5
From base model to chat and reasoning models
- First stage: next-token prediction on huge data (what we just did, at small scale)
- Chat model: supervised fine-tuning on user/assistant turns
- Coding model: base model fine-tuned on coding-specific data
- Reasoning model: base model then reinforcement learning
- Fine-tuning methods mentioned: LoRA, QLoRA
- Tool calling: model generates a call, function runs, output appended to context
- Model weights are what you download, not a vector database
Glossary
- Vocabulary
- All tokens the model can use, each with an ID.
- Dropout
- Randomly zeroing a fraction of values during training to reduce overfitting.
- Hyperparameter
- A setting chosen by humans, such as learning rate or batch size.
- Temperature
- Divisor on logits that controls randomness when sampling.
- Residual connection
- Adding a layer's input back to its output.
- torch.no_grad
- Context that stops gradient tracking.
- MPS
- Apple GPU backend in PyTorch, used instead of CUDA on Macbooks.