We implement a bigram character-level language model, which we will further complexify in followup videos into a modern Transformer language model, like GPT. In this video, the focus is on (1) introducing torch.Tensor and its subtleties and use in efficiently evaluating neural networks and (2) the overall framework of language modeling that includes model training, sampling, and the evaluation of a loss (e.g. the negative log likelihood for classification).
Working through Andrej Karpathy's Neural Networks: Zero to Hero, lecture 2 (makemore).
Run top to bottom.
N,stoi,itos,xs,ys,Wandprobsare each rebound several times as the model is rebuilt: the 28-row table becomes 27, five training examples become 228,146. The firstWis unseeded; every other random draw uses seed2147483647.
A dataset of names¶
One name per line, lowercase a to z, 2 to 15 characters long. The task is
generative: learn the distribution the names come from, then sample new ones
that could plausibly belong to it.
Each name holds several training examples. isabella says that i can start
a name, s can follow i, a can follow l, and the name can end after
a. A character-level model reads all of those out of it.
words = open('names.txt', 'r').read().splitlines()
words[:10]
len(words)
min(len(w) for w in words)
max(len(w) for w in words)
Bigrams¶
The simplest language model: predict the next character from the current one and nothing else. Every adjacent pair in a name is one observation of $P(c_{t+1} \mid c_t)$.
zip(w, w[1:]) alone misses two facts per name: which character starts it and
that it ends. Padding with <S> and <E> makes both into bigrams, so a name
of $L$ characters yields $L + 1$ of them. Over the dataset that is
$\sum_w (|w| + 1) = 228{,}146$.
Counting them in a dict gives the model outright. The top of the table is
endings and openings: n<E> 6,763, a<E> 6,640, an 5,438, <S>a 4,410.
#Bigram model development as an example.
for w in words[:1]:
for ch1, ch2 in zip(w, w[1:]):
print(ch1, ch2)
# using start and end tokens to mark the beginning and end of a word
for w in words[:1]:
chs = ['<S>'] + list(w) + ['<E>']
for ch1, ch2 in zip(chs, chs[1:]):
print(ch1, ch2)
# tracking the counts of each bigram in a dictionary
b = {}
for w in words:
chs = ['<S>'] + list(w) + ['<E>']
for ch1, ch2 in zip(chs, chs[1:]):
bigram = (ch1, ch2)
b[bigram] = b.get(bigram, 0) + 1
#print(ch1, ch2)
sorted(b.items(), key=lambda kv: -kv[1])
Counts as a tensor¶
A dict keyed by pairs is the right data in the wrong shape. A $28 \times 28$
int32 tensor N, with N[i, j] counting character j after character i,
supports row slicing, normalisation and sampling in one call each. stoi maps
a to z onto 0 to 25 and the two markers onto 26 and 27; itos inverts it
for the labels.
The heatmap shows the waste. The <E> row is all zeros, since nothing follows
the end, and so is the <S> column, since nothing precedes the start: 55 of
784 cells that can never be nonzero. The darkest cells are n<E>, a<E> and
an, matching the dict.
# using pytorch to create a 2d array of bigram counts
import torch
N = torch.zeros((28, 28), dtype=torch.int32)
chars = sorted(list(set(''.join(words))))
stoi = {s:i for i,s in enumerate(chars)}
stoi['<S>'] = 26
stoi['<E>'] = 27
for w in words:
chs = ['<S>'] + list(w) + ['<E>']
for ch1, ch2 in zip(chs, chs[1:]):
ix1 = stoi[ch1]
ix2 = stoi[ch2]
N[ix1, ix2] += 1
itos = {i:s for s,i in stoi.items()}
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(16,16))
plt.imshow(N, cmap='Blues')
for i in range(28):
for j in range(28):
chstr = itos[i] + itos[j]
plt.text(j, i, chstr, ha='center', va='bottom', color='gray')
plt.text(j, i, N[i,j].item(), ha='center', va='top', color='gray')
plt.axis('off')
One special token¶
<S> and <E> never occupy the same position, so a single . at index 0 can
do both jobs. Letters shift to 1 to 26 and the table drops to
$27 \times 27 = 729$ cells, with no structurally empty row or column.
Row 0 is now the distribution of first letters and column 0 the distribution
of last letters. Row 0 sums to 32,033, one start per name. 102 cells are still
zero because the pair never occurs in the data (qb, jq, vf), which
matters once the model is scored.
# lets clean things up using a similar structure with only one special token
N = torch.zeros((27, 27), dtype=torch.int32)
chars = sorted(list(set(''.join(words))))
stoi = {s:i+1 for i,s in enumerate(chars)}
stoi['.'] = 0
itos = {i:s for s,i in stoi.items()}
for w in words:
chs = ['.'] + list(w) + ['.']
for ch1, ch2 in zip(chs, chs[1:]):
ix1 = stoi[ch1]
ix2 = stoi[ch2]
N[ix1, ix2] += 1
plt.figure(figsize=(16,16))
plt.imshow(N, cmap='Blues')
for i in range(27):
for j in range(27):
chstr = itos[i] + itos[j]
plt.text(j, i, chstr, ha='center', va='bottom', color='gray')
plt.text(j, i, N[i,j].item(), ha='center', va='top', color='gray')
plt.axis('off')
Sampling the first character¶
Normalise row 0 into a probability vector:
$$p_c = \frac{N_{0,c}}{\sum_{c'} N_{0,c'}}$$
a gets $4410 / 32033 = 0.1377$. torch.multinomial draws indices with those
weights, and the torch.Generator seeded with 2147483647 makes the draw
repeatable. It returns c, which had probability $0.0481$.
#first row
N[0]
# create probability
p = N[0].float()
p = p / p.sum()
p
# sample from the distribution with torch.multinomial with a Generator
g = torch.Generator().manual_seed(2147483647) # for reproducibility
ix = torch.multinomial(p, num_samples=1, replacement=True, generator=g).item()
itos[ix]
A full sampler with smoothing¶
Normalising every row at once gives P, the whole model: 729 numbers, row $i$
the distribution over what follows character $i$. A name starts at row 0,
draws, moves to the row of the character drawn, and stops on a draw of ..
Two details in the first cell:
keepdim=True.P.sum(1, keepdim=True)is $27 \times 1$ and broadcasts across columns, dividing each row by its own total. Without it the sum is a 27-vector that broadcasts as a $1 \times 27$ row, dividing column $j$ by row $j$'s total. No error, wrong model: rows no longer sum to 1.N + 1. Laplace smoothing. One fake count per cell gives the 102 unseen bigrams a small nonzero probability. Without it, a single unseen pair in a name makes that name's likelihood 0 and its log likelihood $-\infty$.
The samples are poor: cexze, staiyaubrtthrigotai. One character of context
cannot know how long the name already is or what came two steps back. They are
still better than uniform over 27 symbols; how much better is what the loss
measures.
P = (N+1).float()
P /= P.sum(1, keepdim=True)
g = torch.Generator().manual_seed(2147483647) # for reproducibility
for i in range(10):
out = []
ix = 0
while True:
p = P[ix]
ix = torch.multinomial(p, num_samples=1, replacement=True, generator=g).item()
out.append(ix)
if ix == 0:
break
print(''.join(itos[i] for i in out))
Negative log likelihood¶
A good model assigns high probability to the data it should generate. Treating bigrams as independent, the likelihood of the training set is the product of the probabilities the model gives each one:
$$L(\theta) = \prod_{i=1}^{n} P_\theta(y_i \mid x_i)$$
228,146 factors below 1 underflow any float. Logs fix that, turn the product into a sum, and leave the maximiser unchanged since $\log$ is monotonic. Negate so that lower is better, divide by $n$ so the number does not scale with the dataset:
$$\text{NLL} = -\frac{1}{n} \sum_{i=1}^{n} \log P_\theta(y_i \mid x_i)$$
0 for a model that is always certain and right; $\log 27 = 3.2958$ for uniform guessing.
The count table scores $2.4546$, perplexity $e^{2.4546} \approx 11.6$: on average as uncertain as a uniform choice among 11.6 characters. Two caveats. That figure includes the $+1$ smoothing, which costs a little: raw counts score $2.4540$, the best any bigram model can do on this data. And it is measured on the training set; there is no held-out split.
# GOAL: maximize likelihood of the data w.r.t. model parameters (statistical modeling)
# equivalent to maximizing the log likelihood (because log is monotonic)
# equivalent to minimizing the negative log likelihood
# equivalent to minimizing the average negative log likelihood
# log(a*b*c) = log(a) + log(b) + log(c)
log_likelihood = 0.0
n = 0
for w in words:
chs = ['.'] + list(w) + ['.']
for ch1, ch2 in zip(chs, chs[1:]):
ix1 = stoi[ch1]
ix2 = stoi[ch2]
prob = P[ix1, ix2].item()
logprob = torch.log(P[ix1, ix2]).item()
log_likelihood += logprob
n += 1
#print(f"{ch1}{ch2}: {prob:.4f} ({logprob:.4f})")
print(f"Log Likelihood: {log_likelihood}")
nnl = -log_likelihood
print(f"Negative Log Likelihood: {nnl}")
print(f"Average Negative Log Likelihood: {nnl/n}")
The same model as a neural network¶
Same task, different parameterisation: instead of counting, let gradient
descent find the 729 numbers. The training set is the bigrams as index pairs,
input xs and label ys. Only emma for now, so five examples: .e, em,
mm, ma, a..
# create the training set of all the bigrams in the dataset
xs, ys = [], []
for w in words[:1]:
chs = ['.'] + list(w) + ['.']
for ch1, ch2 in zip(chs, chs[1:]):
ix1 = stoi[ch1]
ix2 = stoi[ch2]
print(f"{ch1}{ch2}: {ix1} {ix2}")
xs.append(ix1)
ys.append(ix2)
xs = torch.tensor(xs)
ys = torch.tensor(ys)
xs
ys
One-hot inputs¶
An index is a label, not a magnitude: m = 13 is not 2.6 times e = 5.
F.one_hot turns index $k$ into a 27-vector with a single 1 at position $k$.
The image shows the five rows, one lit cell each, column 13 lit twice for the
two m inputs.
.float() is required: one_hot returns int64, and the next step multiplies
by float weights.
import torch.nn.functional as F
xenc = F.one_hot(xs, num_classes=27).float()
xenc
xenc.shape
plt.imshow(xenc)
xenc.dtype
A linear layer of 27 neurons¶
W is $27 \times 27$: 27 neurons, each with 27 weights, no bias, no
nonlinearity. xenc @ W is $(5, 27) \cdot (27, 27) \to (5, 27)$, entry
$(i, j)$ the activation of neuron $j$ on example $i$.
With a one-hot input the product selects a row:
$$\mathbf{e}_k^\top W = W_{k,:}$$
So the layer is a lookup table, row $k$ holding the scores for what follows
character $k$, the same shape as N. Output rows 2 and 3 are identical
because both inputs are m. This W is unseeded and replaced below, so its
numbers mean nothing.
# weights for the neuron
W = torch.randn((27, 27), requires_grad=True)
xenc @ W
# (5, 27) @ (27, 27) = (5, 27)
Softmax¶
The 27 outputs are arbitrary reals; a distribution needs nonnegative entries summing to 1. Read them as log counts, exponentiate to get something count-like, normalise each row:
$$p_{ij} = \frac{e^{z_{ij}}}{\sum_{k} e^{z_{ik}}}$$
Those two lines are the softmax. Every step is differentiable, so a loss on
$p$ can send gradients back to W. The correspondence with the count model is
direct: counts plays N, probs plays P, and $W_{ij} = \log(N_{ij} + 1)$
reproduces the smoothed table exactly.
logits = xenc @ W # logits are the raw scores for each class (27 classes in this case)
counts = logits.exp() # counts are the unnormalized probabilities for each class (27 classes in this case), equivalent N
probs = counts / counts.sum(1, keepdim=True) # probabilities are the normalized counts for each class (27 classes in this case), equivalent P
probs
probs[0]
Scoring a forward pass¶
The same pipeline with W drawn from the seeded generator, so the numbers
below repeat on every run. The loop scores the five emma bigrams one at a
time:
| bigram | input | label | $p$ of label | NLL |
|---|---|---|---|---|
.e |
0 | 5 | 0.0123 | 4.399 |
em |
5 | 13 | 0.0181 | 4.015 |
mm |
13 | 13 | 0.0267 | 3.623 |
ma |
13 | 1 | 0.0737 | 2.608 |
a. |
1 | 0 | 0.0150 | 4.201 |
Mean $3.7693$, worse than the $3.2958$ of uniform guessing: random weights give
confident wrong distributions, not flat ones. mm and ma share input 13 and
so share a distribution; one row of W has to serve both labels.
# SUMMARY ------------------------------>>>>
xs
ys
# randomly initialize 27 neurons' weights. each neuron receives 27 inputs
g = torch.Generator().manual_seed(2147483647)
W = torch.randn((27, 27), generator=g)
xenc = F.one_hot(xs, num_classes=27).float() # input to the network: one-hot encoding
logits = xenc @ W # predict log-counts
counts = logits.exp() # counts, equivalent to N
probs = counts / counts.sum(1, keepdims=True) # probabilities for next character
# btw: the last 2 lines here are together called a 'softmax'
probs.shape
nlls = torch.zeros(5)
for i in range(5):
# i-th bigram:
x = xs[i].item() # input character index
y = ys[i].item() # label character index
print('\n--------\n')
print(f'bigram example {i+1}: {itos[x]}{itos[y]} (indexes {x},{y})')
print('input to the neural net:', x)
print('output probabilities from the neural net:', probs[i])
print('label (actual next character):', y)
p = probs[i, y]
print('probability assigned by the net to the the correct character:', p.item())
logp = torch.log(p)
print('log likelihood:', logp.item())
nll = -logp
print('negative log likelihood:', nll.item())
nlls[i] = nll
print('=========')
print('average negative log likelihood, i.e. loss =', nlls.mean().item())
Vectorising the loss¶
W is redrawn from the same seed with requires_grad=True, so PyTorch records
the graph. The per-example loop becomes one indexing expression:
probs[torch.arange(5), ys] pairs row $i$ with column ys[i], gathering the
five probabilities from the table above. Same $3.7693$.
xs
ys
g = torch.Generator().manual_seed(2147483647) # for reproducibility
W = torch.randn((27, 27), generator=g, requires_grad=True) # randomly initialize 27 neurons' weights. each neuron receives 27 inputs
#forward pass
xenc = F.one_hot(xs, num_classes=27).float() # input to the network: one-hot encoding
logits = xenc @ W # predict log-counts
counts = logits.exp() # counts, equivalent to N
probs = counts / counts.sum(1, keepdim=True) # probabilities for next character
probs[0,5], probs[1,13], probs[2,13], probs[3,1], probs[4,0]
torch.arange(5)
loss = -probs[torch.arange(5), ys].log().mean()
loss
Gradients and one update¶
W.grad = None before backward(), for the reason in notebook 01: gradients
accumulate. Softmax followed by NLL has a compact gradient with respect to the
logits:
$$\frac{\partial\, \text{NLL}}{\partial z_{ij}} = \frac{1}{n}\left(p_{ij} - \mathbb{1}[j = y_i]\right)$$
Every wrong class is pushed down by its probability, the right one pulled up by $1 - p$. Through $z = XW$ that becomes $\nabla_W = X^\top \nabla_z$, so row $k$ of the gradient sums over the examples whose input is $k$. Checkable against the output:
W.grad[0, 5]$= (0.0123 - 1)/5 = -0.1975$: the.elabel pulled up.W.grad[0, 0]$= 0.0607/5 = 0.0121$: a wrong class pushed down.- Rows 2, 3 and 4 (
b,c,d) are zero: no example has them as input.
W.data += -0.1 * W.grad steps against the gradient, outside the autograd
graph.
#bacward pass
W.grad = None # set the gradient to zero before backward pass
loss.backward() # compute the gradient of the loss w.r.t. the weights W
W.grad
W.data += -0.1 * W.grad # update the weights using gradient descent with a learning rate of 0.1
Ten more steps¶
Forward, reset, backward, update, repeated. The loss falls about $0.02$ per step, $3.7492$ to $3.5703$. Step 1 prints $3.7492$ rather than $3.7693$ because the cell above already applied one update. A learning rate of $0.1$ is small for this loss; the full-data run below uses 50.
for i in range(10):
#forward pass
xenc = F.one_hot(xs, num_classes=27).float() # input to the network: one-hot encoding
logits = xenc @ W # predict log-counts
counts = logits.exp() # counts, equivalent to N
probs = counts / counts.sum(1, keepdim=True) # probabilities for next character
loss = -probs[torch.arange(5), ys].log().mean()
#bacward pass
W.grad = None # set the gradient to zero before backward pass
loss.backward() # compute the gradient of the loss w.r.t. the weights W
W.data += -0.1 * W.grad # update the weights using gradient descent with a learning rate of 0.1
print(f"step {i+1}, loss: {loss.item():.4f}")
Training on every bigram¶
Every bigram in the dataset, the same $\sum_w (|w| + 1)$ counted earlier, and
W reset to the seeded draw.
# create the dataset
xs, ys = [], []
for w in words:
chs = ['.'] + list(w) + ['.']
for ch1, ch2 in zip(chs, chs[1:]):
ix1 = stoi[ch1]
ix2 = stoi[ch2]
xs.append(ix1)
ys.append(ix2)
xs = torch.tensor(xs)
ys = torch.tensor(ys)
num = xs.nelement()
print('number of examples: ', num)
# initialize the 'network'
g = torch.Generator().manual_seed(2147483647)
W = torch.randn((27, 27), generator=g, requires_grad=True)
Regularisation as smoothing¶
$\text{mean}(W^2) = 0.9665$ at initialisation, near 1 since each entry is $\mathcal{N}(0, 1)$.
The training loss adds $0.01 \cdot \text{mean}(W^2)$. Pulling W towards zero
pulls every row of logits towards a constant, which softmax turns into the
uniform distribution: the same effect as adding fake counts to N. The
coefficient plays the role of the $+1$; raising it smooths harder.
The learning rate is 50 because the gradient is an average over all 228,146
examples and each row of W gets only its own share. Row q has 272
examples, so its gradient carries a factor of about
$272 / 228146 \approx 0.0012$.
100 steps take the loss from $3.7686$ to $2.4901$. The printed figure includes the penalty, about $0.015$ by the end, so the NLL part is about $2.475$: above the count model's $2.4546$ and still falling.
(W**2).mean()
# gradient descent
for k in range(100):
# forward pass
xenc = F.one_hot(xs, num_classes=27).float() # input to the network: one-hot encoding
logits = xenc @ W # predict log-counts
counts = logits.exp() # counts, equivalent to N
probs = counts / counts.sum(1, keepdims=True) # probabilities for next character
loss = -probs[torch.arange(num), ys].log().mean() + 0.01*(W**2).mean() # loss = average negative log likelihood + regularization
print(loss.item())
# backward pass
W.grad = None # set to zero the gradient
loss.backward()
# update
W.data += -50 * W.grad
Sampling from the trained network¶
The count sampler with P[ix] swapped for a forward pass on a one-hot ix,
and the generator reseeded to the same 2147483647.
cexze, konimittain, llayn and ka match the count sampler draw for draw;
the second name diverges at its tail, ityha against itynn. Same seed and
nearly the same 729 probabilities, so the draws coincide until one lands near a
boundary between two characters.
Two routes to one model. Counting gives the closed-form answer; gradient descent approaches it. The gradient route is the one that survives more context: a count table over $k$ preceding characters needs $27^k$ rows, while a network can share parameters across them.
# finally, sample from the 'neural net' model
g = torch.Generator().manual_seed(2147483647)
for i in range(5):
out = []
ix = 0
while True:
# ----------
# BEFORE:
#p = P[ix]
# ----------
# NOW:
xenc = F.one_hot(torch.tensor([ix]), num_classes=27).float()
logits = xenc @ W # predict log-counts
counts = logits.exp() # counts, equivalent to N
p = counts / counts.sum(1, keepdims=True) # probabilities for next character
# ----------
ix = torch.multinomial(p, num_samples=1, replacement=True, generator=g).item()
out.append(itos[ix])
if ix == 0:
break
print(''.join(out))