Large Language Model Internals
Karpathy’s zero to hero
We’re statistically modeling language, with the goal of accurately predicting text.
Bigram model
Ths simplest model is a bigram model: modeling pairs of characters, using one to predict the next.
Assume we take a piece of text and represent each character in the alphabet with an integer, creating a vocabulary with size N.
As we read, we can create an NxN matrix of next token predictions, initialized with all entries as zero.
For each character (i) we read, we can peek at the next character (j), and increment entry at index (i, j) in our matrix.
We can normalize each row (i) by its sum, creating a probability distribution of the next character (token) given the current character (i).
We can repeatedly sample from this distribution to produce concrete integers, representing tokens in our initial vocabulary.
We use the sampled token to index a new row in our matrix, sampling from the next set of probabilities.
Our vocabulary contains special tokens representing the beginning or end of a stream of generations. We can reuse the same token for both.
Vector manipulations
Learn them.
Tensor broadcasting
Binary or elementwise operations require compatible size.
Incompatible sizes may be made compatible by broadcasting dimensions under certain rules.
Broadcasting rules in pytorch for example dictate:
- each tensor must have at least one dimension
- for each dimension, the dimensions must be equal, one must be one, or one must not exist.
Tensors are “stretched” (using the single existing dimension, or vectors of zeroes(?)) to make them compatible, without data copies.
import torch
# Create tensors with different shapes
a = torch.tensor([1, 2, 3]) # Shape: (3,)
b = torch.tensor([[4], [5], [6]]) # Shape: (3, 1)
# Broadcasting happens automatically in operations
c = a + b # Shape: (3, 3)
# Result:
# [[5, 6, 7],
# [6, 7, 8],
# [7, 8, 9]]
# The scalar 2 is broadcast to match matrix shape
d = torch.ones((2, 3)) * 2 # Shape: (2, 3)
# Result:
# [[2, 2, 2],
# [2, 2, 2]]
Vector sum
In pytorch, P.sum() sums all values over a matrix.
When we want to element-wise divide a row by its sum in pytorch, we need to sum over the each row producing an Nx1 vector, then broadcast that to an NxN matrix compatible with our original shape.
To do this, we can P.sum(0, keepdim=True) in pytorch.
With keepdim=True, this returns a tensor with size (N, 1). with keepdim=False it returns a tensor with size (N)
import torch
# Create a 3x4 matrix
matrix = torch.tensor([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
# Sum without keepdim - reduces dimension
row_sums = matrix.sum(1, keepdim=False) # Shape: (3,)
print(f"Without keepdim: {row_sums.shape}") # torch.Size([3])
# Sum with keepdim - preserves dimension
row_sums_kept = matrix.sum(1, keepdim=True) # Shape: (3, 1)
print("Row sums with keepdim:")
print(row_sums_kept) # tensor([[10],
# [26],
# [42]])
print(f"With keepdim: {row_sums_kept.shape}") # torch.Size([3, 1])
# Broadcasting elementwise division example
normalized = matrix / row_sums_kept # Shape: (3, 4)
print("Normalized matrix (rows sum to 1):")
print(normalized)
Index vectors with vectors using arange
For a tensor with size (N, N) you can extract multiple elements at once in both dimensions using vectors:
# Create a 4x4 example matrix
matrix = torch.tensor([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
])
print("Original matrix:")
print(matrix)
# Create index vectors using arange
xs = torch.arange(0, 4) # tensor([0, 1, 2, 3])
ys = torch.arange(0, 4) # tensor([0, 1, 2, 3])
# Extract diagonal elements using vector indexing
probs = matrix[xs, ys] # tensor([1, 6, 11, 16])
print("\nDiagonal elements:")
print(probs)
# output:
# Original matrix:
# tensor([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12],
# [13, 14, 15, 16]])
# Diagonal elements:
# tensor([ 1, 6, 11, 16]) -- i.e. (0,0), (1,1), (2,2), (3,3) from the original matrix
Quality and loss
We want to maximize the probability for all our predictions. To do so we can effectively maximize the product of all predictions.
Taking the log is equivalent to this since log is a monotonic function. Maximizing the log is equivalent to minimizing the negative log likelihood.
The log of the product of all probabilities is equal to the sum of the log of all probabilities because log(a*b) = log(a)+log(b).
This gives us a function with domain 0 to 1, codomain -infinity to 0.
Model smoothing - NaN / Infinity
If a model has never seen a particular sequence, the loss for that sequence is zero, making the negative log likelihood negative infinity.
We can work around this by adding a constant across all counts prior to calculating the probability distribution.
This forces non-zero probabilities for all tokens. Adding a greater constant has a greating smoothing effect, i.e. makes unseen token sequences more likely.
One hot encoding
Given our vocabulary with size N, we can convert our integer prediction of the next token into a vector using “one hot” encoding.
We obtain a vector with size N, with all values zero except the index of our integer set to 1.
We can use this as an input to a neural network.
Note: row index lookup in an embedding table is equivalent to one hot encoding and multiplication by the resulting vector, as it masks all other values.
Neuron activation - weights and biases
Each neuron in a neural network has weights and optionally a constant bias, represented as floating point numbers.
A neuron outputs a weighted sum with a bias, y = Wx + b, where W and x are tensors and b is a constant.
We typically pass this through a non-linear activation function to obtain outputs.
A two layer neural network with a non-linear activation function can be proven to be a universal function approximator.
Batch neuron inputs
Note that we can easily input multiple examples by adding rows to our input encoding text.
Instead of a 1 x N input vector multipled by a N x 1 set of weights, we can do M x N input by N x 1 weights to give M x 1 outputs, 1 per sample.
Neuron outputs
We want something like the negative log likelihood for the neuron outputs, but the structure above doesn’t guarantee that.
We want a function that gives probabilities between 0 and 1, and we want the sum of probabilities for a next token for a particular current token to sum to 1.
We can exponentiate our current function, interpreting the neural network output as the log count of the actual occurrences of a token.
We can sum and normalize each row to obtain our probability distribution. Exponentiating and normalizing like this is also called a softmax.
The values before normalization such that they sum to 1 are called the logits.
Training: optimizing loss via gradient descent (aka backpropagation)
Imagine we take some values and perform a series of operations on them — addition, multiplication, exponentation.
A = 1
B = 2
C = A * B
D = C ** 2
E = B * C + D
We can see how this creates a graph of functions, where D depends on C which depends on A and B.
We can construct our graph such that all the individual operations are differentiable.
We can use the chain rule to calculate partial deriviates of each variable (weight, bias) with respect to the final loss.
To improve (reduce) our loss, we adjust values by a small amount in the opposite of the direction of the gradient.
Intuitively this makes sense — the derivative represents the “slope” of a curve, and we want to “descend” the slope to the local minimum value. To descend, you go in the opposite direction of the slope.
How much do we adjust by? We call this the learning rate.
The derivative is instantaneous and only correct in an epsilon neighborhood around the given value so we can’t adjust by too large a step.
We do want to train quickly though. We have to balance this tension. We can experiment to find good learning rates, and decay them as we approach the minimum loss to avoid overshoot.
Regularization loss
TODO: why is this useful?
We already added some smoothing to counts earlier. With neurons, the equivalent is when weights are zero, because logits are 0, resulting in a uniform probability distribution after exponentiation.
We can add a term to our loss function which forces minimizing weights to zero by adding a positive term any time W is non zero, e.g. (W**2).mean() * (strength)
This can help control numerical explosion of the weights as there’s a counteracting force pushing them to zero (is there any other justification?).
Generalization: multi-layer perceptrons
2003 paper (Bengio, Ducharme, Vincent, and Jauvin) describes embedding words into multidimensional feature vectors.
We can feed a sequence of words into neurons, with each word embedded into a feature vector via table lookup.
We connect the embedding vectors to a hidden layer of arbitrary size (hyperparameter/design choice to optimize).
The hidden layer connects to an output layer with neurons the size of our vocabulary.
We need to ensure compatible matrix sizes when doing multiplication.
E.g. with a vocab size of 17000, hidden dimension 100, batch size 32, context length 3 for prediction, 2 dimensional embeddings, we have:
- (32, 3, 2) input tensor
- (17000, 2) embedding table
- (6, 100) hidden layer
- (32, 17000) dimensional output — probabilities for each word, per batch item
In this case we view the input tensor as a (32, 3*2) = (32, 6) to make it compatible with our (6, 100) hidden layer for multiplication.
We can also use pytorch’s cross entropy in place of our own implementation of negative log likelihood.
This allows hardware optimization e.g. using fused kernels on GPUs to reduce memory copies and maximize compute throughput.
Large logits = infinity
We added model smoothing to avoid negative infinity negative log likelihoods.
We have a similar problem if our neurons output very large values prior to softmax.
When we exponentiate a very large value, we may exceed the numerical limits of our data types, producing positive infinity.
Negative logits with large magnitude don’t have the same issue. They produce numerically small, non-zero values after exponentiation.
We can offset all logits by a constant before exponentation to avoid this issue.
To avoid large positive values, we can substract the value of largest positive logit from all logits.
This operation forces all values to be <= 0, ensuring well-behaved numerical output.
Minibatches and gradient quality
We may not want or be able to pass all examples from a text through a single forward training pass.
We can batch up data, randomly indexing into the training data set and selecting samples.
Our gradient for each batch is no longer representative of the full data set, so we may introduce more variation in the loss as we train.
It’s empirically better to use an approximate gradient and make more steps (inherently using less computation) than a more precise gradient with fewer steps.
It’s possible if our batch size is too small, the noise will dominate. As always, a balance.
Initial loss and neuron death
If our initial logits from random weights are very extreme, we will have extreme initial loss.
We can minimize the weights at initialization to avoid this.
We want to avoid exactly zero to avoid neuron death, where a neuron contributes nothing to outputs and cannot learn.
Tokenization
In practice, we do not use characters or words as our vocabulary for embeddings or token predictions.
Common tokenizers use sub-word tokens. Byte pair encoding is another form of encoding gaining popularity.
Attention
We can use context history by taking an average over the predictions for a given sequence.
We can implement this using matrix multiplication as a weighted aggregation.
In the simplest form:
import torch
import torch.nn.functional as F
# batch, time, channel
B, T, C = 4, 8, 2
# data
x = torch.randint(5, (B, T, C)).float()
head_size = 16
query = nn.Linear(C, head_size, bias=False)
key = nn.Linear(C, head_size, bias=False)
q = query(x) # (B, T, H)
k = key(x) # (B, T, H)
wei = q @ k.transpose(-2, -1) # (B, T, H) @ (B, H, T) = (B, T, T)
# lower triangular matrix
tril = torch.tril(torch.ones(T,T))
# upper triangular matrix with infinities
wei = wei.masked_fill(tril.logical_not(), float("-inf"))
# after softmax, infinities become 0 and each value divided by sum
# becomes lower triangular
wei = F.softmax(wei, dim=-1)
# (B, T, T) @ (B, T, C) = (B, T, C)
# weighted sum over entries with "future" masked out
wei @ x
As a pytorch module with forward pass:
import torch
import torch.nn.functional as F
class Head(nn.Module):
def __init__(self, n_embed, head_size):
super().__init__
self.query = nn.Linear(n_embed, head_size, bias=False)
self.key = nn.Linear(n_embed, head_size, bias=False)
self.value = nn.Linear(n_embed, head_size, bias=False)
def forward(self, x):
B, T, C = x.shape
q = self.query(x)
k = self.key(x)
wei = q @ k.transpose(-2, -1)
tril = torch.tril(torch.ones(T, T))
wei = wei.masked_fill(tril.logical_not(), float("-inf"))
wei = F.softmax(wei, dim=-1) # (B, T, T)
v = self.value(x) # (B, T, C)
out = wei @ v # (B, T, C)
return out
Multi head Attention
We can group multiple attention heads, dividing the total desired dimensional output by the number of heads.
class MultiHeadAttention(nn.Module):
def __init__(self, num_heads, n_embed, head_size):
super().__init__()
self.heads = ModuleList([Head(n_embed, head_size) for _ in range(num_heads)])
def forward(self, x)
return torch.cat([h(x) for h in self.heads], dim=-1)
The benefit of this is we can learn separate communication channels without averaging between them lossing information granularity.
Language model head
We may also introduce a level on indirection using a language modeling head to map the attention head embedding dimension back to the model vocabulary size for final logit output:
class FeedForward(nn.Module):
def __init__(self, n_embed):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_embed, n_embed),
nn.ReLU(),
)
def forward(self, x):
return self.net(x)
class BigramLanguageModel(nn.Module):
def __init__(self, vocab_size, n_embed, num_heads, head_size):
self.token_embedding_table = nn.Linear(vocab_size, n_embed)
self.position_embedding_Table = nn.Linear(vocab_size, n_embed)
self.sa_heads = MultiHeadAttention(num_heads, n_embed, head_size)
self.ffn = FeedForward(n_embed)
self.lm_head = nn.Linear(n_embed, vocab_size)
def forward(self, idx, targets=None):
B, T = idx.shape
token_emb = self.token_embedding_table(B, T) # B, T, vocab_size
positional_emb = self.positional_embedding_table(B, T) # B, T, vocab_size
x = token_emb + positional_emb # B, T, vocab_size
x = self.sa_heads(x) # B, T, n_embed
x = self.ffn(x)
logits = self.lm_head(x) # B, T, vocab_size
if targets is None:
loss = None
else:
B, T, C = logits.shape
logits = logits.view(B*T, C)
targets = targets.view(B*T)
loss = N.cross_entropy(logits, targets)
return logits, loss
We can also sample from this model:
# idx is B, T
def generate(self, idx, max_num_tokens):
for _ in range(max_num_tokens):
logits, _ = self(idx) # B, T, C
logits = logits[:, -1, :] # last time step! B, C
probs = F.softmax(logits, -1) # exponentiate and normalize logits for probs -> B, C
idx_next = torch.multinomial(probs, num_samples=1) # B, 1
idx = torch.cat((idx, idx_next), dim=-1) # B, T+1
Transformer block
We can stack up attention heads with feed forward networks to create transformer decoder blocks.
Note: a feed forward with a linear layer and ReLU is essentially an approximator for any non linear combination.
class Block(nn.Module):
def __init__(self, n_embed, n_head):
super().__init__()
head_size = n_embed // n_head
self.attn = MultiHeadAttention(n_head, n_embed, head_size)
self.ffn = FeedForward(n_embed)
def forward(self, x):
x = self.attn(x)
x = self.ffn(x)
return x
Now we can layer these blocks in place of a single Multi Head Attention:
class BigramLanguageModel(nn.Module):
def __init__(self, vocab_size, n_embed, n_head, head_size):
self.token_embedding_table = nn.Linear(vocab_size, n_embed)
self.position_embedding_Table = nn.Linear(vocab_size, n_embed)
self.blocks = nn.Sequential(
Block(n_embed, n_head),
Block(n_embed, n_head),
Block(n_embed, n_head),
Block(n_embed, n_head),
)
self.ffn = FeedForward(n_embed)
self.lm_head = nn.Linear(n_embed, vocab_size)
Residuals
With deep or large networks, we may see vanishing gradients as we train.
One mitigation to this problem is residual blocks.
Each layer transforms input weights. We can add a skip connection that bypasses this transformation and do addition over the parts.
We implement these connections by adding a linear projection layer to our multi head attention, and adjusting our block to contain the required skip connection:
class MultiHeadAttention(nn.Module):
def __init__(self, num_heads, n_embed, head_size):
super().__init__()
self.proj = nn.Linear(n_embed, n_embed) # NEW
self.heads = ModuleList([Head(n_embed, head_size) for _ in range(num_heads)])
def forward(self, x)
out = torch.cat([h(x) for h in self.heads], dim=-1)
out = self.proj(out) # NEW
return out
class Block(nn.Module):
def __init__(self, n_embed, n_head):
super().__init__()
head_size = n_embed // n_head
self.attn = MultiHeadAttention(n_head, n_embed, head_size)
self.ffn = FeedForward(n_embed)
def forward(self, x):
x = x + self.attn(x) # <-- changed
x = x + self.ffn(x) # <-- changed
return x
The original paper also uses a feed forward network with dimensionality change across two layers. We can adjust this like below:
class FeedForward(nn.Module):
def __init__(self, n_embed):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_embed, 4 * n_embed),
nn.ReLU(),
nn.Linear(4 * n_embed, n_embed),
)
def forward(self, x):
return self.net(x)
Layer norm
Layer norm is one of the final missing pieces compared to the “attention is all you need” paper.
We add this pre-input on each transformer block, and as a final output of the stack of blocks.
class Block(nn.Module):
def __init__(self, n_embed, n_head):
super().__init__()
head_size = n_embed // n_head
self.attn = MultiHeadAttention(n_head, n_embed, head_size)
self.ffn = FeedForward(n_embed)
self.ln1 = nn.LayerNorm(n_embed)
self.ln2 = nn.LayerNorm(n_embed)
def forward(self, x):
x = x + self.attn(self.ln1(x)) # <-- changed
x = x + self.ffn(self.ln2(x)) # <-- changed
return x
class BigramLanguageModel(nn.Module):
def __init__(self, vocab_size, n_embed, n_head, head_size):
self.token_embedding_table = nn.Linear(vocab_size, n_embed)
self.position_embedding_Table = nn.Linear(vocab_size, n_embed)
self.blocks = nn.Sequential(
Block(n_embed, n_head),
Block(n_embed, n_head),
Block(n_embed, n_head),
nn.LayerNorm(n_embed),
)
self.lm_head = nn.Linear(n_embed, vocab_size)
Dropout
To avoid overfitting, we can randomly disable communication by masking some weights.
It’s possible to do this before linear recombination at the end of each of our layers/blocks.
class FeedForward(nn.Module):
def __init__(self, n_embed):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_embed, 4 * n_embed),
nn.ReLU(),
nn.Linear(4 * n_embed, n_embed),
nn.Dropout(n_embed)
)
def forward(self, x):
return self.net(x)
class Head(nn.Module):
def __init__(self, n_embed, head_size):
super().__init__
self.query = nn.Linear(n_embed, head_size, bias=False)
self.key = nn.Linear(n_embed, head_size, bias=False)
self.value = nn.Linear(n_embed, head_size, bias=False)
self.dropout = nn.Dropout(n_embed)
def forward(self, x):
B, T, C = x.shape
q = self.query(x)
k = self.key(x)
wei = q @ k.transpose(-2, -1)
tril = torch.tril(torch.ones(T, T))
wei = wei.masked_fill(tril.logical_not(), float("-inf"))
wei = F.softmax(wei, dim=-1) # (B, T, T)
wei = self.dropout(wei)
v = self.value(x) # (B, T, C)
out = wei @ v # (B, T, C)
return out
class MultiHeadAttention(nn.Module):
def __init__(self, num_heads, n_embed, head_size):
super().__init__()
self.heads = ModuleList([Head(n_embed, head_size) for _ in range(num_heads)])
self.proj = nn.Linear(n_embed, n_embed)
self.dropout = nn.Dropout(n_embed) # NEW
def forward(self, x)
out = torch.cat([h(x) for h in self.heads], dim=-1)
out = self.proj(out)
out = self.dropout(out) # NEW
return out