LLM from scratch
These are my notes on building a large language model from scratch.
Overview
These are my full notes on developing an LLM from scratch. It involves building the model architecture, explaining each component of the model, and training it on a basic dataset. The goal is to understand the building blocks of LLMs and how they are trained to generate text.
Project Link: https://github.com/kanjurer/emergence
Architecture
The following is LLM architecture derived from Attention is All You Need paper.

Components of LLM
Embedding
class: TokenAndPositionEmbedding

- Trainable component of LLM that maps tokens into a vector space.
Attention
class: CausalSelfAttention

- Q, K, V are matrices.
- Attention scores of the head matrix:
- We divide by because each head operates on vectors of dimension .
- Next, apply softmax to get attention weights matrix:
- Then, get attention output matrix:
- Finally, concatenate the outputs of all heads to get the final output matrix.
Causal Mask: Although we can directly use Attention scores to compute “attention weights” by applying softmax, we need to apply something called a Causal Mask to ensure that the model does not attend to future tokens, which is a fancy term for “please do not cheat and look at the next token when predicting the current token”. Turns out, a lower triangular matrix is a good way to implement this.
MLP
class: MLP

Transformer Block
class: TransformerBlock
If x is the embedding input to the transformer then,
An alternative approach could be
But this approach is not as effective as the first one, which uses residual connections. The residual connections help in training deep networks by allowing gradients to flow through the network more easily. Paper
Model
class: TransformerModel
Now putting it all together, where L is number of transformer blocks, d is the embedding dimension, and h is the number of attention heads, we have the following equations for the model:
Training LLM
Relevant python files: Trainer, Checkpointing, Optimizer and Datasets, Tokenizer
- We first use a dataset and tokenize it and text positions to numerical IDs.
- Then we feed these into model to get an output, and compute the loss to compute gradient and update the model parameters using AdamW optimizer.
- We batch the dataset to speed up training.
- We go through the dataset multiple times (epochs) to improve the model performance.
Cross Entropy Loss
- On a higher level, we compute the loss between predicted output and the actual output.
- Remember, the model takes in a sequence of tokens and predicts the next token in the sequence. So, we compute the loss between the predicted token and the actual next token in the sequence.
AdamW Optimizer
- This is used to perform gradient descent (like we do using SGD).
- When we compute the loss, we also compute the gradients which updates the
.gradattribute of the model. - Then we use the optimizer to update the model parameters using these gradients.