simply, it makes more of the things that you give it
example: give it a bunch of names, and it will create name-like words based on those names
at its core, it is a character-level bigram language model
Some music for you to listen to while you read:
Breaking down "character-level bigram language model":
It might feel like I threw a bunch of words together to sound cool. Maybe? But here's the breakdown of what it actually means to be a "character-level bigram language model"
Character-Level:
we are dealing with characters, and not whole words
we deal with whole words after creating a tokenizer for words, as well as reproducing GPT2 (from karpathy's NN zero to hero series. Makemore is part of that series)
Bigram Language Model:
we look at a word two characters at a time using a sliding window
why we do this? goal is to predict what character is likely to follow of after another one.
It's a pretty weak and simple language model, but its a good start for us
Name Generation Method 1: Bigram Counting
We won't be going into depth about the bigram counting method since my focus is the neural network part of it, but here's the essence of the counting method (crucial for understanding how NN version works):
you run a sliding window (2 chars at a time) throughout the entire dataset of names, and store the frequency of each of the bigram pairs
for example: the combination ab appears 50 times, and the combination ac appears 5 times
If we just look at ab and ac in isolation, if we have a character a, it is much likely to be followed by a b than a c
We use this principle, but for all aa, ab, ac, ad, ... az and a.
a. signifies ending of a word (yes, that's a character we look for as well. When we encounter this . character, that means the name is complete and we should stop. Otherwise it'd be an infinite name loop)
Name 1 of 5
emma
Bigram counts0 pairs counted
em
0
mm
0
ma
0
mi
0
il
0
ly
0
el
0
ll
0
la
0
st
0
te
0
you then convert counts for each of the pairs beginning with a certain character to probability using normalization
Example bigram counts for a
aa
42 divided by 400
Probability 0.105
ab
128 divided by 400
Probability 0.320
ac
54 divided by 400
Probability 0.135
Other
160 divided by 400
Probability 0.400
az
16 divided by 400
Probability 0.040
↘↘↓↙↙
Row total42 + 128 + 54 + 160 + 16 = 400
0.105 + 0.320 + 0.135 + 0.400 + 0.040 = 1.000
Other groups the remaining pairs that start with a.
you then sample the next character based on probability of occurrence (like the ab and ac example above) using torch.multinomial function
Draw a character after m
01
a
25%
i
50%
m
25%
Wider segments have a greater chance of being picked.
you start off with a . (meaning word started), and you end when you see another .
Build a name from .
.
Draw after .
01
e
60%
m
20%
s
20%
The starting dot selects the first-letter row.
congratulations, you just generated a made-up name using probabilities
Why is this approach weak:
sliding window approach only looks at 2 chars at a time, completley ignoring all of the characters earlier in a word - so it's like guessing the next character at best without any particular "strategy" as to how its doing that
this will be fixed when we implement self attention using transformers in my next writing piece by following karpathy's "gpt from scratch" tutorial
Name Generation Method 2: Bigram Neural Networks
we use Neural Networks as a way to "learn" the patterns that the bigram model operates on (instead of directly using counts normalization) to reach about the same results that the counting bigram model achieved
High Level Implementation:
Our implementation will use a very very simple NN with:
27 input nodes (one hot encoded)
27 output nodes (resemble probabilities after softmax)
27 inputsW (27 × 27)27 outputs
Every input connects to every output. The highlighted weight, W[e, a], connects e to a.
the model uses its internal weights (27x27 tensor) and does a matrix multiplication with one-hot encoded input to obtain logits
logits are basically the way the model represents a score of how likely is this character (the one you one-hot encoded) to be followed by another character
since our neural network has 27 inputs, the way we input is suppose you want to input the character "e" to see what the predicted next character is. What you do is set all input neurons to 0, except the one at position 5 (representing e). this is called one-hot encoding.
how we get the probabilities:
currently, we have logits, which are ~ log(counts), as the outputs of the neural network. Counts here doesn't represent the counts in the counting model, but an abstract count that is roughly representative of the frequency
To make it into the (representative) counts, we exponentiate the logits to get counts. Remember, elogx=x
after exponentiating, we normalize it just like the counting bigram model to get a row that resembles the probabilities of the next character in the sequence. (This process is called Softmax btw)
x_encoded (1 × 27)@W (27 × 27)
x
In
.
a
…
y
z
0
.
-2.1
0.2
…
0.2
0.4
0
a
1.5
0.0
…
-0.3
0.2
⋮
⋮
⋮
1
e
0.3
-1.2
…
2.1
0.5
⋮
⋮
⋮
0
z
-0.1
0.3
…
-0.8
-0.5
logit[a] = 0 + … + 1 × (-1.2) + … + 0 = -1.2
Next
.
a
…
y
z
Logits
0.3
-1.2
…
2.1
0.5
exp
1.350
0.301
…
8.166
1.649
Prob.
0.037
0.008
…
0.224
0.045
x_encoded @ W = row e of W
The 27 input bits line up with the rows of W. Only the bit for e is 1.
Why do we do one hot encoding?
Neural networks like to take inputs in a way that makes sense to accomodate all possible types of inputs
the best way we can do this here is have an input for each of the characters that we can input.
Index 5
.
0
a
0
b
0
c
0
d
0
e
1
f
0
g
0
h
0
i
0
j
0
k
0
l
0
m
0
n
0
o
0
p
0
q
0
r
0
s
0
t
0
u
0
v
0
w
0
x
0
y
0
z
0
e sets position 5 to 1. The other 26 positions stay at 0.
The Loss Function:
this is the signle number that defines how good our language model is
looking at a particular word, our model would be good (less loss) if we trained it on the name emma, and during prediction, it successfully gives high probability to m after e, m after m, a after m, and . after a (em -> mm -> ma -> a.)
to condense down the quality of a model for a particular name, we multiply the product of probabilities of all of these different entries above (proba of getting m after inputting e, and so on), and this probability should be as high as possible
so, the essence of our loss function depends on the product of probabilities (likelihood of occurrence)
How likely is emma?Pick a transition to change its example probability. The starting dot adds the first-letter prediction.
If it's multiplication of probabilities, do we stop here:
nahh, there's a lot of challenges if we use multiplication of these probabilities at face value like:
since each probability is smaller than 1, its multiplication with the training dataset combined will be soooooooo small. How to make small things (less than 1) big? log. (no sus)
Multiply 8 probabilities of 0.5
Raw product 0.58
3.9063e-3
Sum of logs 8 × ln(0.5)
-5.545
Each extra prediction halves the raw product and adds the same term to the sum of logs.
multiplying is a relatively expensive operation. What isn't? log (because terms are added due to log property)
so if the gods are pointing you to use log, why not use log?
Loss Function Finally: Average Negative Log Likelihood:
say whaaa? ok lets go step by step
based on the previous "hints", instead of multiplying the raw probabilities of the predictions, we'll multiply the probabilities and log them for the names
So, if a, b, c, ... are probabilities, we do log(abc) = log(a) + log(b) + log(c) to turn a multiplication into an addition. We now have log likelihood"*
Two routes to the same log likelihood
Multiply, then take the log
ln(0.5 × 0.25 × 0.80) = ln(0.10000) ≈ -2.303
Take the logs, then add
ln(0.5) + ln(0.25) + ln(0.80) ≈ -2.303
since log is monotonic, it doesn't really impact the way the counts and probabilities interact on a fundamental level
now, since all of the log of proba products will be negative, as can be seen on the log(x) graph below (for inputs smaller than 1), we will multiply them by -1 to get a positive number for loss to deal with. We now have negative log likelihood
The curve stays below zero for 0 < x < 1 and reaches zero at x = 1.
We can stop here, and optimize this number and make it as small as possible (making it so that the probability numbers themselves need to be bigger to prevent the log from going smaller). However, we can do a little bit better
Since the current definition of our loss encapsulates the entire training dataset, it might create cases where some names are very poorly trained on while the rest of them are very well trained on.
To solve this problem, lets take an average for ALL of the probabilities that we find in this way, and divide the final negative log likelihood by this number, for it to tell a good story about the entire training set on a smaller level. We now have average negative log likelihood
What now after finding the loss?
you don't ask that question, you should already know the answer to it. Optimize the heck out of it using backpropagation
loss gets less, predictions become more and more true to the training set, and you start to see values that are more and more name-like.
Watch the training loss fall
Learning rate
70
Full-batch updates
500
Training names
32,033
Character pairs
228,146
Mean training loss
3.7563
Probability of m after e
2.42%
The model starts with random weights. Each update computes the mean negative log likelihood over all character pairs, then subtracts its gradient multiplied by the learning rate from the weights.
Here's what the optimized version of the NN predictions look like in action:
Generate a name with the trained bigram model
32,033 training names · 500 updates
.
Start at the dot and draw the next character from its softmax probabilities.
Softmax probabilities after the start dot
01
Wider intervals are more likely to be picked.
a
13.77%
k
9.25%
m
7.92%
j
7.56%
All 27 softmax probabilities
Softmax exponentiates each logit after subtracting the largest logit, then divides by the sum of those scores.
Next
Logit
Probability
End dot
-5.037
0.02%
a
1.575
13.77%
b
0.358
4.08%
c
0.524
4.81%
d
0.616
5.28%
e
0.517
4.78%
f
-0.784
1.3%
g
-0.311
2.09%
h
-0.044
2.73%
i
-0.435
1.84%
j
0.976
7.56%
k
1.177
9.25%
l
0.544
4.91%
m
1.023
7.92%
n
0.227
3.58%
o
-0.841
1.23%
p
-0.573
1.61%
q
-2.297
0.29%
r
0.585
5.12%
s
0.812
6.41%
t
0.360
4.08%
u
-2.463
0.24%
v
-0.887
1.17%
w
-1.090
0.96%
x
-1.920
0.42%
y
-0.535
1.67%
z
0.017
2.9%
Use Next character to follow one draw at a time. Select a character in the sequence to revisit its draw.
See the code that was used to generate the NN
Read-only
exportconst TOKENS = ".abcdefghijklmnopqrstuvwxyz";
exportconst SIZE = TOKENS.length;
exportconst SEED = 6767676767;
exportconst LEARNING_RATE = 70;
exportconst EPOCHS = 500;
exportconst NAME_LIMIT = 32;
exporttype TrainingData = {
counts: ArrayLike<number>;
totals: ArrayLike<number>;
pairCount: number;
};
exporttype Dataset = {
words: string[];
xs: Uint8Array;
ys: Uint8Array;
counts: Float64Array;
totals: Float64Array;
pairCount: number;
baseline: number;
};
exportfunction dataset(text: string): Dataset {
const words = text.trim().split(/\r?\n/).filter(Boolean);
if (!words.length || words.some((word) => !/^[a-z]+$/.test(word))) {
thrownew Error("Names must contain lowercase letters a–z only.");
}
const length = words.reduce((sum, word) => sum + word.length + 1, 0);
const xs = new Uint8Array(length),
ys = new Uint8Array(length);
const counts = new Float64Array(SIZE * SIZE),
totals = new Float64Array(SIZE);
let offset = 0;
for (const word of words) {
const chars = `.${word}.`;
for (let i = 0; i < chars.length - 1; i++) {
const x = TOKENS.indexOf(chars[i]),
y = TOKENS.indexOf(chars[i + 1]);
xs[offset] = x;
ys[offset++] = y;
counts[x * SIZE + y]++;
totals[x]++;
}
}
let baseline = 0;
counts.forEach((count, index) => {
if (count)
baseline -=
(count * Math.log(count / totals[Math.floor(index / SIZE)])) / length;
});
return { words, xs, ys, counts, totals, pairCount: length, baseline };
}
// Mulberry32, with Box–Muller for normal weights. Reproducible here, not torch's RNG.exportfunction random(seed: number) {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) | 0;
let value = Math.imul(state ^ (state >>> 15), 1 | state);
value ^= value + Math.imul(value ^ (value >>> 7), 61 | value);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
exportfunction initialize(seed = SEED) {
const rng = random(seed),
weights = new Float64Array(SIZE * SIZE);
for (let i = 0; i < weights.length; i++) {
weights[i] =
Math.sqrt(-2 * Math.log(1 - rng())) * Math.cos(2 * Math.PI * rng());
}
return weights;
}
exportfunction softmaxRow(weights: Float64Array, row: number) {
const logits = weights.slice(row * SIZE, (row + 1) * SIZE);
const max = Math.max(...logits);
const scores = logits.map((value) => Math.exp(value - max));
const sum = scores.reduce((a, b) => a + b, 0);
const probs = scores.map((value) => value / sum);
const logProbs = logits.map((value) => value - max - Math.log(sum));
return { logits, scores, sum, probs, logProbs, max };
}
exportfunction evaluate(weights: Float64Array, data: TrainingData, strength = 0) {
const gradient = new Float64Array(SIZE * SIZE); // W.grad = None: fresh buffer, no accumulation.let dataLoss = 0,
penalty = 0;
for (let row = 0; row < SIZE; row++) {
const { probs, logProbs } = softmaxRow(weights, row);
for (let col = 0; col < SIZE; col++) {
const index = row * SIZE + col;
dataLoss -= (data.counts[index] * logProbs[col]) / data.pairCount;
penalty += (strength * weights[index] ** 2) / weights.length;
gradient[index] =
(data.totals[row] * probs[col] - data.counts[index]) / data.pairCount +
(2 * strength * weights[index]) / weights.length;
}
}
const loss = dataLoss + penalty;
if (!Number.isFinite(loss) || gradient.some((v) => !Number.isFinite(v))) {
thrownew Error(
"Training reached non-finite values. Reset and try a smaller learning rate.",
);
}
return { gradient, dataLoss, penalty, loss };
}
exporttype Snapshot = ReturnType<typeof step>;
exportfunction step(
weights: Float64Array,
data: TrainingData,
rate: number,
strength = 0,
) {
const before = weights.slice();
const result = evaluate(before, data, strength);
const after = before.map(
(value, index) => value - rate * result.gradient[index],
);
if (after.some((value) => !Number.isFinite(value)))
thrownew Error("Weights are not finite. Reset to restart.");
return { before, after, ...result, rate, strength };
}
/** Reverse each operation for ONE example, including its 1/N contribution to mean loss. */exportfunction backwardExample(
weights: Float64Array,
x: number,
y: number,
examples: number,
) {
const row = softmaxRow(weights, x);
const dProbs = new Float64Array(SIZE);
dProbs[y] = -1 / (row.probs[y] * examples);
const dSum = (-dProbs[y] * row.scores[y]) / row.sum ** 2;
const dScores = dProbs.map((value) => value / row.sum + dSum);
const dLogits = dScores.map((value, index) => value * row.scores[index]);
return { ...row, dProbs, dSum, dScores, dLogits };
}
exportfunction draw(probs: Float64Array, rng: () => number) {
const u = rng();
let sum = 0;
for (let index = 0; index < probs.length; index++) {
sum += probs[index];
if (u < sum) return { index, u };
}
return { index: probs.length - 1, u };
}
exporttype GenerationDraw = { input: number; output: number; u: number };
exportfunction generate(
weights: Float64Array,
rng: () => number,
limit = NAME_LIMIT,
onDraw?: (sample: GenerationDraw) => void,
) {
let name = "",
row = 0;
for (let i = 0; i < limit; i++) {
const { index, u } = draw(softmaxRow(weights, row).probs, rng);
onDraw?.({ input: row, output: index, u });
row = index;
if (row === 0) return { name, ended: true };
name += TOKENS[row];
}
return { name, ended: false };
}