Building makemore Part 2: MLP
Overview
Andrej Karpathy builds a character-level MLP language model inspired by Bengio et al. (2003), replacing the bigram model’s one-character context with a learned embedding for each character and a neural network that predicts the next character. He implements the dataset, embedding lookup, hidden and output layers, cross-entropy training, mini-batches, learning-rate tuning, and train/dev/test evaluation; a model with 10-dimensional embeddings and 200 hidden units reaches about 2.17 validation loss, improving on the bigram model’s 2.45.
Key takeaways
- A learned embedding plus an MLP avoids the exponential growth of a context-count table by sharing statistical patterns across characters and contexts.
- For three context characters, two-dimensional embeddings flatten from shape 32-by-3-by-2 to 32-by-6 with tensor.view, which changes the tensor’s interpretation without copying storage.
- Mini-batches trade exact gradients for noisier estimates; batches of 32 enable many faster updates and can outperform computing a full-dataset gradient less often.
- A logarithmic learning-rate range test can locate a useful step size: Karpathy searched from 0.001 to 1 and found roughly 0.1 effective before reducing it during later training.
- Training loss and validation loss answer different questions: training loss measures fit to optimization data, while dev loss helps detect underfitting or overfitting and select hyperparameters.
- The final model’s 10-dimensional character embeddings and 200-neuron hidden layer reach about 2.17 validation loss, versus 2.45 for the earlier bigram model.
Chapters
- The previous makemore model predicts a character from only the immediately preceding character.
- A count table grows exponentially with context length: 27 contexts for one character, 729 for two, and about 20,000 for three.
- Karpathy introduces an MLP language model based on Bengio et al. (2003) to learn from longer context without a huge count table.
- The paper embeds each of 17,000 words in a 30-dimensional space, with backpropagation learning the embedding vectors.
- Similar words or words used in similar contexts can become nearby, allowing the model to transfer patterns to phrases absent from training.
- For a three-word context, the architecture concatenates three embeddings, applies a fully connected hidden layer and tanh, then predicts the next word with a softmax.
- Karpathy reads about 32,000 names and maps the 27-character vocabulary, including the dot used for sequence boundaries.
- The block size sets the context length; with a block size of three, three characters predict the fourth.
- A rolling context padded with dots generates input tensor X and target tensor Y, producing 32 examples from the first five names and about 228,000 examples from the full dataset.
- The embedding matrix C has 27 rows, one per character, and initially uses two values per character.
- Indexing C with an input tensor retrieves all character embeddings at once, turning a 32-by-3 input into a 32-by-3-by-2 tensor.
- A one-hot vector multiplied by C produces the same embedding as row lookup, but direct indexing is simpler and faster.
- With a three-character context and two-dimensional embeddings, the hidden layer receives six inputs and initially has 100 neurons.
- torch.cat can concatenate each context position’s embedding, while torch.unbind makes that approach work for variable block sizes.
- Tensor.view reshapes the 32-by-3-by-2 embedding tensor into 32-by-6 without copying its underlying storage, unlike concatenation.
- The hidden layer adds a shared bias and applies tanh, producing 32-by-100 activations.
- The output layer maps 100 hidden activations to 27 logits, one for each possible next character.
- Exponentiating and normalizing logits creates a probability distribution for each training example.
- The target character’s probability is selected from each row, and the negative average log probability gives the negative log-likelihood loss.
- torch.nn.functional.cross_entropy computes the same classification loss directly from logits and targets.
- The fused implementation can avoid intermediate tensors and use a more efficient backward pass.
- It is numerically stable: subtracting the maximum logit before exponentiation prevents overflow when logits become very large.
- Karpathy zeros parameter gradients, calls loss.backward(), and updates parameters by subtracting the learning rate times each gradient.
- The initial network has about 3,400 parameters, so it can drive loss very low on just 32 examples.
- Loss cannot reach zero when an identical context, such as the all-dot start, has multiple valid next characters in the training data.
- Instead of calculating gradients over all 228,000 examples each step, the training loop samples mini-batches using random indices.
- A batch size of 32 gives noisier gradient estimates, but allows many more updates in the same amount of time.
- Karpathy tests learning rates from 0.001 to 1 on a logarithmic scale, plots loss against learning-rate exponent, and identifies about 0.1 as a useful starting rate.
- After repeated mini-batch updates at learning rate 0.1, Karpathy reduces the rate by a factor of 10 as training plateaus.
- The model reaches about 2.3 loss, improving on the prior bigram model’s 2.45.
- A lower training loss alone does not establish better generalization because larger networks can memorize their training examples.
- The dataset is divided by name into roughly 80% training, 10% development, and 10% test data.
- Gradient descent updates model parameters on the training split; the dev split guides choices such as hidden size and embedding dimension.
- The test split is reserved for infrequent final evaluation because repeatedly checking it can indirectly overfit model decisions to the test data.
- Training and dev losses near 2.3 suggest the 100-neuron model is underfitting rather than memorizing the training set.
- Increasing the hidden layer to 300 neurons raises the model from about 3,400 to about 10,000 parameters.
- Limited improvement points to possible bottlenecks, including mini-batch noise and the two-dimensional character embeddings.
- Before increasing embedding dimensionality, Karpathy plots the learned two-dimensional coordinates of the 27 characters.
- Vowels cluster together, suggesting the model treats them as similar in the contexts relevant to next-character prediction.
- The dot boundary token and the letter q occupy distinctive locations, showing that training has organized the initially random embeddings.
- Karpathy expands embeddings from two to 10 dimensions, uses a 200-neuron hidden layer, and updates the input width to 30 for three context characters.
- With about 11,000 parameters and continued learning-rate adjustments, training and dev losses separate slightly as the model begins to overfit.
- The best reported validation loss is about 2.17; suggested tuning knobs include context length, embedding size, hidden width, batch size, and learning-rate schedule.
- Generation begins with a context of dots, predicts next-character probabilities with softmax, and samples an index using torch.multinomial.
- The context window shifts after each sampled character until the boundary token appears; examples such as “ham” and “joes” look more name-like than bigram samples.
- Karpathy points to a Google Colab notebook so learners can run, inspect, and change the PyTorch model without installing Jupyter or dependencies locally.
Transcript excerpt
0:00 hi everyone today we are continuing our implementation of makemore now in the last lecture we implemented the bigram language model and we implemented it both using counts and also using a super simple neural network that had a single linear layer now this is the jupyter notebook that we built out last lecture and we saw that the way we approached this is that we looked at only the single previous character and we predicted the distribution for the character that would go next in the sequence and we did that by taking counts and normalizing them into probabilities so that each row here sums to one now this is all well and good if you only have one character of previous context and this works and it's approachable the problem with this model of course is that
0:46 the predictions from this model are not very good because you only take one character of context so the model didn't produce very name like sounding things now the problem with this approach though is that if we are to take more context into account when predicting the next character in a sequence things quickly blow up and this table the size of this table grows and in fact it grows exponentially with the length of the context because if we only take a single character at a time that's 27 possibilities of context but if we take two characters in the past and try to predict the third one suddenly the number of rows in this matrix you can look at it that way is 27 times 27 so there's 729 possibilities for what could have come in the context if we take three characters as the context suddenly we have
1:34 20 000 possibilities of context and so there's just way too many rows of
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Andrej Karpathy.