Krys Newman/AI Frontier/02 · Language Modeling - Building makemore Search

Notebook 02

02 · Language Modeling - Building makemore

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).

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, W and probs are each rebound several times as the model is rebuilt: the 28-row table becomes 27, five training examples become 228,146. The first W is unseeded; every other random draw uses seed 2147483647.

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.

In [1]:
words = open('names.txt', 'r').read().splitlines()
words[:10]
Out[1]:
['emma',
 'olivia',
 'ava',
 'isabella',
 'sophia',
 'charlotte',
 'mia',
 'amelia',
 'harper',
 'evelyn']
In [2]:
len(words)
Out[2]:
32033
In [3]:
min(len(w) for w in words)
Out[3]:
2
In [4]:
max(len(w) for w in words)
Out[4]:
15

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.

In [5]:
#Bigram model development as an example.

for w in words[:1]:
    for ch1, ch2 in zip(w, w[1:]):
        print(ch1, ch2)
e m
m m
m a
In [6]:
# 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)
<S> e
e m
m m
m a
a <E>
In [7]:
# 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)
In [8]:
sorted(b.items(), key=lambda kv: -kv[1])
Out[8]:
[(('n', '<E>'), 6763),
 (('a', '<E>'), 6640),
 (('a', 'n'), 5438),
 (('<S>', 'a'), 4410),
 (('e', '<E>'), 3983),
 (('a', 'r'), 3264),
 (('e', 'l'), 3248),
 (('r', 'i'), 3033),
 (('n', 'a'), 2977),
 (('<S>', 'k'), 2963),
 (('l', 'e'), 2921),
 (('e', 'n'), 2675),
 (('l', 'a'), 2623),
 (('m', 'a'), 2590),
 (('<S>', 'm'), 2538),
 (('a', 'l'), 2528),
 (('i', '<E>'), 2489),
 (('l', 'i'), 2480),
 (('i', 'a'), 2445),
 (('<S>', 'j'), 2422),
 (('o', 'n'), 2411),
 (('h', '<E>'), 2409),
 (('r', 'a'), 2356),
 (('a', 'h'), 2332),
 (('h', 'a'), 2244),
 (('y', 'a'), 2143),
 (('i', 'n'), 2126),
 (('<S>', 's'), 2055),
 (('a', 'y'), 2050),
 (('y', '<E>'), 2007),
 (('e', 'r'), 1958),
 (('n', 'n'), 1906),
 (('y', 'n'), 1826),
 (('k', 'a'), 1731),
 (('n', 'i'), 1725),
 (('r', 'e'), 1697),
 (('<S>', 'd'), 1690),
 (('i', 'e'), 1653),
 (('a', 'i'), 1650),
 (('<S>', 'r'), 1639),
 (('a', 'm'), 1634),
 (('l', 'y'), 1588),
 (('<S>', 'l'), 1572),
 (('<S>', 'c'), 1542),
 (('<S>', 'e'), 1531),
 (('j', 'a'), 1473),
 (('r', '<E>'), 1377),
 (('n', 'e'), 1359),
 (('l', 'l'), 1345),
 (('i', 'l'), 1345),
 (('i', 's'), 1316),
 (('l', '<E>'), 1314),
 (('<S>', 't'), 1308),
 (('<S>', 'b'), 1306),
 (('d', 'a'), 1303),
 (('s', 'h'), 1285),
 (('d', 'e'), 1283),
 (('e', 'e'), 1271),
 (('m', 'i'), 1256),
 (('s', 'a'), 1201),
 (('s', '<E>'), 1169),
 (('<S>', 'n'), 1146),
 (('a', 's'), 1118),
 (('y', 'l'), 1104),
 (('e', 'y'), 1070),
 (('o', 'r'), 1059),
 (('a', 'd'), 1042),
 (('t', 'a'), 1027),
 (('<S>', 'z'), 929),
 (('v', 'i'), 911),
 (('k', 'e'), 895),
 (('s', 'e'), 884),
 (('<S>', 'h'), 874),
 (('r', 'o'), 869),
 (('e', 's'), 861),
 (('z', 'a'), 860),
 (('o', '<E>'), 855),
 (('i', 'r'), 849),
 (('b', 'r'), 842),
 (('a', 'v'), 834),
 (('m', 'e'), 818),
 (('e', 'i'), 818),
 (('c', 'a'), 815),
 (('i', 'y'), 779),
 (('r', 'y'), 773),
 (('e', 'm'), 769),
 (('s', 't'), 765),
 (('h', 'i'), 729),
 (('t', 'e'), 716),
 (('n', 'd'), 704),
 (('l', 'o'), 692),
 (('a', 'e'), 692),
 (('a', 't'), 687),
 (('s', 'i'), 684),
 (('e', 'a'), 679),
 (('d', 'i'), 674),
 (('h', 'e'), 674),
 (('<S>', 'g'), 669),
 (('t', 'o'), 667),
 (('c', 'h'), 664),
 (('b', 'e'), 655),
 (('t', 'h'), 647),
 (('v', 'a'), 642),
 (('o', 'l'), 619),
 (('<S>', 'i'), 591),
 (('i', 'o'), 588),
 (('e', 't'), 580),
 (('v', 'e'), 568),
 (('a', 'k'), 568),
 (('a', 'a'), 556),
 (('c', 'e'), 551),
 (('a', 'b'), 541),
 (('i', 't'), 541),
 (('<S>', 'y'), 535),
 (('t', 'i'), 532),
 (('s', 'o'), 531),
 (('m', '<E>'), 516),
 (('d', '<E>'), 516),
 (('<S>', 'p'), 515),
 (('i', 'c'), 509),
 (('k', 'i'), 509),
 (('o', 's'), 504),
 (('n', 'o'), 496),
 (('t', '<E>'), 483),
 (('j', 'o'), 479),
 (('u', 's'), 474),
 (('a', 'c'), 470),
 (('n', 'y'), 465),
 (('e', 'v'), 463),
 (('s', 's'), 461),
 (('m', 'o'), 452),
 (('i', 'k'), 445),
 (('n', 't'), 443),
 (('i', 'd'), 440),
 (('j', 'e'), 440),
 (('a', 'z'), 435),
 (('i', 'g'), 428),
 (('i', 'm'), 427),
 (('r', 'r'), 425),
 (('d', 'r'), 424),
 (('<S>', 'f'), 417),
 (('u', 'r'), 414),
 (('r', 'l'), 413),
 (('y', 's'), 401),
 (('<S>', 'o'), 394),
 (('e', 'd'), 384),
 (('a', 'u'), 381),
 (('c', 'o'), 380),
 (('k', 'y'), 379),
 (('d', 'o'), 378),
 (('<S>', 'v'), 376),
 (('t', 't'), 374),
 (('z', 'e'), 373),
 (('z', 'i'), 364),
 (('k', '<E>'), 363),
 (('g', 'h'), 360),
 (('t', 'r'), 352),
 (('k', 'o'), 344),
 (('t', 'y'), 341),
 (('g', 'e'), 334),
 (('g', 'a'), 330),
 (('l', 'u'), 324),
 (('b', 'a'), 321),
 (('d', 'y'), 317),
 (('c', 'k'), 316),
 (('<S>', 'w'), 307),
 (('k', 'h'), 307),
 (('u', 'l'), 301),
 (('y', 'e'), 301),
 (('y', 'r'), 291),
 (('m', 'y'), 287),
 (('h', 'o'), 287),
 (('w', 'a'), 280),
 (('s', 'l'), 279),
 (('n', 's'), 278),
 (('i', 'z'), 277),
 (('u', 'n'), 275),
 (('o', 'u'), 275),
 (('n', 'g'), 273),
 (('y', 'd'), 272),
 (('c', 'i'), 271),
 (('y', 'o'), 271),
 (('i', 'v'), 269),
 (('e', 'o'), 269),
 (('o', 'm'), 261),
 (('r', 'u'), 252),
 (('f', 'a'), 242),
 (('b', 'i'), 217),
 (('s', 'y'), 215),
 (('n', 'c'), 213),
 (('h', 'y'), 213),
 (('p', 'a'), 209),
 (('r', 't'), 208),
 (('q', 'u'), 206),
 (('p', 'h'), 204),
 (('h', 'r'), 204),
 (('j', 'u'), 202),
 (('g', 'r'), 201),
 (('p', 'e'), 197),
 (('n', 'l'), 195),
 (('y', 'i'), 192),
 (('g', 'i'), 190),
 (('o', 'd'), 190),
 (('r', 's'), 190),
 (('r', 'd'), 187),
 (('h', 'l'), 185),
 (('s', 'u'), 185),
 (('a', 'x'), 182),
 (('e', 'z'), 181),
 (('e', 'k'), 178),
 (('o', 'v'), 176),
 (('a', 'j'), 175),
 (('o', 'h'), 171),
 (('u', 'e'), 169),
 (('m', 'm'), 168),
 (('a', 'g'), 168),
 (('h', 'u'), 166),
 (('x', '<E>'), 164),
 (('u', 'a'), 163),
 (('r', 'm'), 162),
 (('a', 'w'), 161),
 (('f', 'i'), 160),
 (('z', '<E>'), 160),
 (('u', '<E>'), 155),
 (('u', 'm'), 154),
 (('e', 'c'), 153),
 (('v', 'o'), 153),
 (('e', 'h'), 152),
 (('p', 'r'), 151),
 (('d', 'd'), 149),
 (('o', 'a'), 149),
 (('w', 'e'), 149),
 (('w', 'i'), 148),
 (('y', 'm'), 148),
 (('z', 'y'), 147),
 (('n', 'z'), 145),
 (('y', 'u'), 141),
 (('r', 'n'), 140),
 (('o', 'b'), 140),
 (('k', 'l'), 139),
 (('m', 'u'), 139),
 (('l', 'd'), 138),
 (('h', 'n'), 138),
 (('u', 'd'), 136),
 (('<S>', 'x'), 134),
 (('t', 'l'), 134),
 (('a', 'f'), 134),
 (('o', 'e'), 132),
 (('e', 'x'), 132),
 (('e', 'g'), 125),
 (('f', 'e'), 123),
 (('z', 'l'), 123),
 (('u', 'i'), 121),
 (('v', 'y'), 121),
 (('e', 'b'), 121),
 (('r', 'h'), 121),
 (('j', 'i'), 119),
 (('o', 't'), 118),
 (('d', 'h'), 118),
 (('h', 'm'), 117),
 (('c', 'l'), 116),
 (('o', 'o'), 115),
 (('y', 'c'), 115),
 (('o', 'w'), 114),
 (('o', 'c'), 114),
 (('f', 'r'), 114),
 (('b', '<E>'), 114),
 (('m', 'b'), 112),
 (('z', 'o'), 110),
 (('i', 'b'), 110),
 (('i', 'u'), 109),
 (('k', 'r'), 109),
 (('g', '<E>'), 108),
 (('y', 'v'), 106),
 (('t', 'z'), 105),
 (('b', 'o'), 105),
 (('c', 'y'), 104),
 (('y', 't'), 104),
 (('u', 'b'), 103),
 (('u', 'c'), 103),
 (('x', 'a'), 103),
 (('b', 'l'), 103),
 (('o', 'y'), 103),
 (('x', 'i'), 102),
 (('i', 'f'), 101),
 (('r', 'c'), 99),
 (('c', '<E>'), 97),
 (('m', 'r'), 97),
 (('n', 'u'), 96),
 (('o', 'p'), 95),
 (('i', 'h'), 95),
 (('k', 's'), 95),
 (('l', 's'), 94),
 (('u', 'k'), 93),
 (('<S>', 'q'), 92),
 (('d', 'u'), 92),
 (('s', 'm'), 90),
 (('r', 'k'), 90),
 (('i', 'x'), 89),
 (('v', '<E>'), 88),
 (('y', 'k'), 86),
 (('u', 'w'), 86),
 (('g', 'u'), 85),
 (('b', 'y'), 83),
 (('e', 'p'), 83),
 (('g', 'o'), 83),
 (('s', 'k'), 82),
 (('u', 't'), 82),
 (('a', 'p'), 82),
 (('e', 'f'), 82),
 (('i', 'i'), 82),
 (('r', 'v'), 80),
 (('f', '<E>'), 80),
 (('t', 'u'), 78),
 (('y', 'z'), 78),
 (('<S>', 'u'), 78),
 (('l', 't'), 77),
 (('r', 'g'), 76),
 (('c', 'r'), 76),
 (('i', 'j'), 76),
 (('w', 'y'), 73),
 (('z', 'u'), 73),
 (('l', 'v'), 72),
 (('h', 't'), 71),
 (('j', '<E>'), 71),
 (('x', 't'), 70),
 (('o', 'i'), 69),
 (('e', 'u'), 69),
 (('o', 'k'), 68),
 (('b', 'd'), 65),
 (('a', 'o'), 63),
 (('p', 'i'), 61),
 (('s', 'c'), 60),
 (('d', 'l'), 60),
 (('l', 'm'), 60),
 (('a', 'q'), 60),
 (('f', 'o'), 60),
 (('p', 'o'), 59),
 (('n', 'k'), 58),
 (('w', 'n'), 58),
 (('u', 'h'), 58),
 (('e', 'j'), 55),
 (('n', 'v'), 55),
 (('s', 'r'), 55),
 (('o', 'z'), 54),
 (('i', 'p'), 53),
 (('l', 'b'), 52),
 (('i', 'q'), 52),
 (('w', '<E>'), 51),
 (('m', 'c'), 51),
 (('s', 'p'), 51),
 (('e', 'w'), 50),
 (('k', 'u'), 50),
 (('v', 'r'), 48),
 (('u', 'g'), 47),
 (('o', 'x'), 45),
 (('u', 'z'), 45),
 (('z', 'z'), 45),
 (('j', 'h'), 45),
 (('b', 'u'), 45),
 (('o', 'g'), 44),
 (('n', 'r'), 44),
 (('f', 'f'), 44),
 (('n', 'j'), 44),
 (('z', 'h'), 43),
 (('c', 'c'), 42),
 (('r', 'b'), 41),
 (('x', 'o'), 41),
 (('b', 'h'), 41),
 (('p', 'p'), 39),
 (('x', 'l'), 39),
 (('h', 'v'), 39),
 (('b', 'b'), 38),
 (('m', 'p'), 38),
 (('x', 'x'), 38),
 (('u', 'v'), 37),
 (('x', 'e'), 36),
 (('w', 'o'), 36),
 (('c', 't'), 35),
 (('z', 'm'), 35),
 (('t', 's'), 35),
 (('m', 's'), 35),
 (('c', 'u'), 35),
 (('o', 'f'), 34),
 (('u', 'x'), 34),
 (('k', 'w'), 34),
 (('p', '<E>'), 33),
 (('g', 'l'), 32),
 (('z', 'r'), 32),
 (('d', 'n'), 31),
 (('g', 't'), 31),
 (('g', 'y'), 31),
 (('h', 's'), 31),
 (('x', 's'), 31),
 (('g', 's'), 30),
 (('x', 'y'), 30),
 (('y', 'g'), 30),
 (('d', 'm'), 30),
 (('d', 's'), 29),
 (('h', 'k'), 29),
 (('y', 'x'), 28),
 (('q', '<E>'), 28),
 (('g', 'n'), 27),
 (('y', 'b'), 27),
 (('g', 'w'), 26),
 (('n', 'h'), 26),
 (('k', 'n'), 26),
 (('g', 'g'), 25),
 (('d', 'g'), 25),
 (('l', 'c'), 25),
 (('r', 'j'), 25),
 (('w', 'u'), 25),
 (('l', 'k'), 24),
 (('m', 'd'), 24),
 (('s', 'w'), 24),
 (('s', 'n'), 24),
 (('h', 'd'), 24),
 (('w', 'h'), 23),
 (('y', 'j'), 23),
 (('y', 'y'), 23),
 (('r', 'z'), 23),
 (('d', 'w'), 23),
 (('w', 'r'), 22),
 (('t', 'n'), 22),
 (('l', 'f'), 22),
 (('y', 'h'), 22),
 (('r', 'w'), 21),
 (('s', 'b'), 21),
 (('m', 'n'), 20),
 (('f', 'l'), 20),
 (('w', 's'), 20),
 (('k', 'k'), 20),
 (('h', 'z'), 20),
 (('g', 'd'), 19),
 (('l', 'h'), 19),
 (('n', 'm'), 19),
 (('x', 'z'), 19),
 (('u', 'f'), 19),
 (('f', 't'), 18),
 (('l', 'r'), 18),
 (('p', 't'), 17),
 (('t', 'c'), 17),
 (('k', 't'), 17),
 (('d', 'v'), 17),
 (('u', 'p'), 16),
 (('p', 'l'), 16),
 (('l', 'w'), 16),
 (('p', 's'), 16),
 (('o', 'j'), 16),
 (('r', 'q'), 16),
 (('y', 'p'), 15),
 (('l', 'p'), 15),
 (('t', 'v'), 15),
 (('r', 'p'), 14),
 (('l', 'n'), 14),
 (('e', 'q'), 14),
 (('f', 'y'), 14),
 (('s', 'v'), 14),
 (('u', 'j'), 14),
 (('v', 'l'), 14),
 (('q', 'a'), 13),
 (('u', 'y'), 13),
 (('q', 'i'), 13),
 (('w', 'l'), 13),
 (('p', 'y'), 12),
 (('y', 'f'), 12),
 (('c', 'q'), 11),
 (('j', 'r'), 11),
 (('n', 'w'), 11),
 (('n', 'f'), 11),
 (('t', 'w'), 11),
 (('m', 'z'), 11),
 (('u', 'o'), 10),
 (('f', 'u'), 10),
 (('l', 'z'), 10),
 (('h', 'w'), 10),
 (('u', 'q'), 10),
 (('j', 'y'), 10),
 (('s', 'z'), 10),
 (('s', 'd'), 9),
 (('j', 'l'), 9),
 (('d', 'j'), 9),
 (('k', 'm'), 9),
 (('r', 'f'), 9),
 (('h', 'j'), 9),
 (('v', 'n'), 8),
 (('n', 'b'), 8),
 (('i', 'w'), 8),
 (('h', 'b'), 8),
 (('b', 's'), 8),
 (('w', 't'), 8),
 (('w', 'd'), 8),
 (('v', 'v'), 7),
 (('v', 'u'), 7),
 (('j', 's'), 7),
 (('m', 'j'), 7),
 (('f', 's'), 6),
 (('l', 'g'), 6),
 (('l', 'j'), 6),
 (('j', 'w'), 6),
 (('n', 'x'), 6),
 (('y', 'q'), 6),
 (('w', 'k'), 6),
 (('g', 'm'), 6),
 (('x', 'u'), 5),
 (('m', 'h'), 5),
 (('m', 'l'), 5),
 (('j', 'm'), 5),
 (('c', 's'), 5),
 (('j', 'v'), 5),
 (('n', 'p'), 5),
 (('d', 'f'), 5),
 (('x', 'd'), 5),
 (('z', 'b'), 4),
 (('f', 'n'), 4),
 (('x', 'c'), 4),
 (('m', 't'), 4),
 (('t', 'm'), 4),
 (('z', 'n'), 4),
 (('z', 't'), 4),
 (('p', 'u'), 4),
 (('c', 'z'), 4),
 (('b', 'n'), 4),
 (('z', 's'), 4),
 (('f', 'w'), 4),
 (('d', 't'), 4),
 (('j', 'd'), 4),
 (('j', 'c'), 4),
 (('y', 'w'), 4),
 (('v', 'k'), 3),
 (('x', 'w'), 3),
 (('t', 'j'), 3),
 (('c', 'j'), 3),
 (('q', 'w'), 3),
 (('g', 'b'), 3),
 (('o', 'q'), 3),
 (('r', 'x'), 3),
 (('d', 'c'), 3),
 (('g', 'j'), 3),
 (('x', 'f'), 3),
 (('z', 'w'), 3),
 (('d', 'k'), 3),
 (('u', 'u'), 3),
 (('m', 'v'), 3),
 (('c', 'x'), 3),
 (('l', 'q'), 3),
 (('p', 'b'), 2),
 (('t', 'g'), 2),
 (('q', 's'), 2),
 (('t', 'x'), 2),
 (('f', 'k'), 2),
 (('b', 't'), 2),
 (('j', 'n'), 2),
 (('k', 'c'), 2),
 (('z', 'k'), 2),
 (('s', 'j'), 2),
 (('s', 'f'), 2),
 (('z', 'j'), 2),
 (('n', 'q'), 2),
 (('f', 'z'), 2),
 (('h', 'g'), 2),
 (('w', 'w'), 2),
 (('k', 'j'), 2),
 (('j', 'k'), 2),
 (('w', 'm'), 2),
 (('z', 'c'), 2),
 (('z', 'v'), 2),
 (('w', 'f'), 2),
 (('q', 'm'), 2),
 (('k', 'z'), 2),
 (('j', 'j'), 2),
 (('z', 'p'), 2),
 (('j', 't'), 2),
 (('k', 'b'), 2),
 (('m', 'w'), 2),
 (('h', 'f'), 2),
 (('c', 'g'), 2),
 (('t', 'f'), 2),
 (('h', 'c'), 2),
 (('q', 'o'), 2),
 (('k', 'd'), 2),
 (('k', 'v'), 2),
 (('s', 'g'), 2),
 (('z', 'd'), 2),
 (('q', 'r'), 1),
 (('d', 'z'), 1),
 (('p', 'j'), 1),
 (('q', 'l'), 1),
 (('p', 'f'), 1),
 (('q', 'e'), 1),
 (('b', 'c'), 1),
 (('c', 'd'), 1),
 (('m', 'f'), 1),
 (('p', 'n'), 1),
 (('w', 'b'), 1),
 (('p', 'c'), 1),
 (('h', 'p'), 1),
 (('f', 'h'), 1),
 (('b', 'j'), 1),
 (('f', 'g'), 1),
 (('z', 'g'), 1),
 (('c', 'p'), 1),
 (('p', 'k'), 1),
 (('p', 'm'), 1),
 (('x', 'n'), 1),
 (('s', 'q'), 1),
 (('k', 'f'), 1),
 (('m', 'k'), 1),
 (('x', 'h'), 1),
 (('g', 'f'), 1),
 (('v', 'b'), 1),
 (('j', 'p'), 1),
 (('g', 'z'), 1),
 (('v', 'd'), 1),
 (('d', 'b'), 1),
 (('v', 'h'), 1),
 (('h', 'h'), 1),
 (('g', 'v'), 1),
 (('d', 'q'), 1),
 (('x', 'b'), 1),
 (('w', 'z'), 1),
 (('h', 'q'), 1),
 (('j', 'b'), 1),
 (('x', 'm'), 1),
 (('w', 'g'), 1),
 (('t', 'b'), 1),
 (('z', 'x'), 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.

In [9]:
# using pytorch to create a 2d array of bigram counts
import torch
In [10]:
N = torch.zeros((28, 28), dtype=torch.int32)
In [11]:
chars = sorted(list(set(''.join(words))))
stoi = {s:i for i,s in enumerate(chars)}
stoi['<S>'] = 26
stoi['<E>'] = 27
In [12]:
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
In [13]:
itos = {i:s for s,i in stoi.items()}
In [14]:
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')
Out[14]:
(np.float64(-0.5), np.float64(27.5), np.float64(27.5), np.float64(-0.5))
No description has been provided for this image

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.

In [15]:
# 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()}
In [16]:
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
In [17]:
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')
Out[17]:
(np.float64(-0.5), np.float64(26.5), np.float64(26.5), np.float64(-0.5))
No description has been provided for this image

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$.

In [18]:
#first row
N[0]
Out[18]:
tensor([   0, 4410, 1306, 1542, 1690, 1531,  417,  669,  874,  591, 2422, 2963,
        1572, 2538, 1146,  394,  515,   92, 1639, 2055, 1308,   78,  376,  307,
         134,  535,  929], dtype=torch.int32)
In [19]:
# create probability 
p = N[0].float()
p = p / p.sum()
p
Out[19]:
tensor([0.0000, 0.1377, 0.0408, 0.0481, 0.0528, 0.0478, 0.0130, 0.0209, 0.0273,
        0.0184, 0.0756, 0.0925, 0.0491, 0.0792, 0.0358, 0.0123, 0.0161, 0.0029,
        0.0512, 0.0642, 0.0408, 0.0024, 0.0117, 0.0096, 0.0042, 0.0167, 0.0290])
In [20]:
# 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]
Out[20]:
'c'

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.

In [21]:
P  = (N+1).float()
P /= P.sum(1, keepdim=True)
In [22]:
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))
cexze.
momasurailezitynn.
konimittain.
llayn.
ka.
da.
staiyaubrtthrigotai.
moliellavo.
ke.
teda.

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.

In [23]:
# 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)
In [24]:
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}")
Log Likelihood: -560001.8846766353
Negative Log Likelihood: 560001.8846766353
Average Negative Log Likelihood: 2.454576826578749

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..

In [25]:
# 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)
.e: 0 5
em: 5 13
mm: 13 13
ma: 13 1
a.: 1 0
In [26]:
xs
Out[26]:
tensor([ 0,  5, 13, 13,  1])
In [27]:
ys
Out[27]:
tensor([ 5, 13, 13,  1,  0])

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.

In [28]:
import torch.nn.functional as F
xenc = F.one_hot(xs, num_classes=27).float()
xenc
Out[28]:
tensor([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
         0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
         0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 0., 0., 0., 0., 0., 0., 0.]])
In [29]:
xenc.shape
Out[29]:
torch.Size([5, 27])
In [30]:
plt.imshow(xenc)
Out[30]:
<matplotlib.image.AxesImage at 0x15c560050>
No description has been provided for this image
In [31]:
xenc.dtype
Out[31]:
torch.float32

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.

In [32]:
# weights for the neuron 

W = torch.randn((27, 27), requires_grad=True)
xenc @ W

# (5, 27) @ (27, 27) = (5, 27)
Out[32]:
tensor([[-1.6556, -1.4008, -0.4439,  0.9298, -2.8385,  1.0672,  1.1399, -1.0212,
          0.7850,  0.5976, -1.2349, -0.2364, -0.4570,  0.3896, -0.9252, -0.2310,
          1.4586, -0.3719,  0.4759, -1.0150, -0.6061,  0.2055, -0.5513,  0.6554,
         -0.8180, -0.3811,  0.0467],
        [ 1.7327, -0.9696,  2.4192,  0.5794, -0.2288,  0.0146, -1.5743,  0.8225,
         -1.6862,  0.7234,  0.2070,  0.4324,  0.5476,  0.3666, -0.5011, -0.1388,
          0.6283,  1.8007, -0.5501,  0.4975, -1.3031,  0.0521, -0.4482,  0.9089,
          0.5918,  1.3810,  0.5611],
        [ 0.4203,  1.5498, -0.4260, -0.1558,  0.5808, -0.5437,  0.9088, -0.0687,
         -0.6508, -1.3291,  0.1824, -0.0134,  0.3184,  2.0384, -0.2683, -0.1499,
         -0.4631, -1.2048,  0.0984,  0.9798, -0.0851, -1.3723, -0.3774, -0.0226,
          0.8379, -0.0819,  1.1431],
        [ 0.4203,  1.5498, -0.4260, -0.1558,  0.5808, -0.5437,  0.9088, -0.0687,
         -0.6508, -1.3291,  0.1824, -0.0134,  0.3184,  2.0384, -0.2683, -0.1499,
         -0.4631, -1.2048,  0.0984,  0.9798, -0.0851, -1.3723, -0.3774, -0.0226,
          0.8379, -0.0819,  1.1431],
        [ 1.0771, -1.9881, -0.5992,  0.2032,  1.5253, -1.0740, -0.5992,  0.3623,
         -0.9904, -0.3122,  0.2997, -3.0004,  0.5356, -0.8411, -1.3777, -2.0712,
          0.9781,  0.2815, -1.4332,  0.8024, -0.6419, -1.3221,  1.4450, -0.1537,
          1.2376, -0.3284, -0.6967]], grad_fn=<MmBackward0>)

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.

In [33]:
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
Out[33]:
tensor([[0.0060, 0.0077, 0.0201, 0.0795, 0.0018, 0.0912, 0.0981, 0.0113, 0.0688,
         0.0570, 0.0091, 0.0248, 0.0199, 0.0463, 0.0124, 0.0249, 0.1349, 0.0216,
         0.0505, 0.0114, 0.0171, 0.0385, 0.0181, 0.0604, 0.0138, 0.0214, 0.0329],
        [0.1026, 0.0069, 0.2037, 0.0324, 0.0144, 0.0184, 0.0038, 0.0413, 0.0034,
         0.0374, 0.0223, 0.0279, 0.0314, 0.0262, 0.0110, 0.0158, 0.0340, 0.1098,
         0.0105, 0.0298, 0.0049, 0.0191, 0.0116, 0.0450, 0.0328, 0.0721, 0.0318],
        [0.0371, 0.1147, 0.0159, 0.0208, 0.0435, 0.0141, 0.0604, 0.0227, 0.0127,
         0.0064, 0.0292, 0.0240, 0.0335, 0.1869, 0.0186, 0.0210, 0.0153, 0.0073,
         0.0269, 0.0649, 0.0224, 0.0062, 0.0167, 0.0238, 0.0563, 0.0224, 0.0764],
        [0.0371, 0.1147, 0.0159, 0.0208, 0.0435, 0.0141, 0.0604, 0.0227, 0.0127,
         0.0064, 0.0292, 0.0240, 0.0335, 0.1869, 0.0186, 0.0210, 0.0153, 0.0073,
         0.0269, 0.0649, 0.0224, 0.0062, 0.0167, 0.0238, 0.0563, 0.0224, 0.0764],
        [0.0869, 0.0041, 0.0162, 0.0362, 0.1360, 0.0101, 0.0162, 0.0425, 0.0110,
         0.0216, 0.0399, 0.0015, 0.0505, 0.0128, 0.0075, 0.0037, 0.0787, 0.0392,
         0.0071, 0.0660, 0.0156, 0.0079, 0.1255, 0.0254, 0.1020, 0.0213, 0.0147]],
       grad_fn=<DivBackward0>)
In [34]:
probs[0]
Out[34]:
tensor([0.0060, 0.0077, 0.0201, 0.0795, 0.0018, 0.0912, 0.0981, 0.0113, 0.0688,
        0.0570, 0.0091, 0.0248, 0.0199, 0.0463, 0.0124, 0.0249, 0.1349, 0.0216,
        0.0505, 0.0114, 0.0171, 0.0385, 0.0181, 0.0604, 0.0138, 0.0214, 0.0329],
       grad_fn=<SelectBackward0>)

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.

In [35]:
# SUMMARY ------------------------------>>>>
In [36]:
xs
Out[36]:
tensor([ 0,  5, 13, 13,  1])
In [37]:
ys
Out[37]:
tensor([ 5, 13, 13,  1,  0])
In [38]:
# randomly initialize 27 neurons' weights. each neuron receives 27 inputs
g = torch.Generator().manual_seed(2147483647)
W = torch.randn((27, 27), generator=g)
In [39]:
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'
In [40]:
probs.shape
Out[40]:
torch.Size([5, 27])
In [41]:
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())
--------

bigram example 1: .e (indexes 0,5)
input to the neural net: 0
output probabilities from the neural net: tensor([0.0607, 0.0100, 0.0123, 0.0042, 0.0168, 0.0123, 0.0027, 0.0232, 0.0137,
        0.0313, 0.0079, 0.0278, 0.0091, 0.0082, 0.0500, 0.2378, 0.0603, 0.0025,
        0.0249, 0.0055, 0.0339, 0.0109, 0.0029, 0.0198, 0.0118, 0.1537, 0.1459])
label (actual next character): 5
probability assigned by the net to the the correct character: 0.012286250479519367
log likelihood: -4.3992743492126465
negative log likelihood: 4.3992743492126465

--------

bigram example 2: em (indexes 5,13)
input to the neural net: 5
output probabilities from the neural net: tensor([0.0290, 0.0796, 0.0248, 0.0521, 0.1989, 0.0289, 0.0094, 0.0335, 0.0097,
        0.0301, 0.0702, 0.0228, 0.0115, 0.0181, 0.0108, 0.0315, 0.0291, 0.0045,
        0.0916, 0.0215, 0.0486, 0.0300, 0.0501, 0.0027, 0.0118, 0.0022, 0.0472])
label (actual next character): 13
probability assigned by the net to the the correct character: 0.018050704151391983
log likelihood: -4.014570713043213
negative log likelihood: 4.014570713043213

--------

bigram example 3: mm (indexes 13,13)
input to the neural net: 13
output probabilities from the neural net: tensor([0.0312, 0.0737, 0.0484, 0.0333, 0.0674, 0.0200, 0.0263, 0.0249, 0.1226,
        0.0164, 0.0075, 0.0789, 0.0131, 0.0267, 0.0147, 0.0112, 0.0585, 0.0121,
        0.0650, 0.0058, 0.0208, 0.0078, 0.0133, 0.0203, 0.1204, 0.0469, 0.0126])
label (actual next character): 13
probability assigned by the net to the the correct character: 0.026691533625125885
log likelihood: -3.623408794403076
negative log likelihood: 3.623408794403076

--------

bigram example 4: ma (indexes 13,1)
input to the neural net: 13
output probabilities from the neural net: tensor([0.0312, 0.0737, 0.0484, 0.0333, 0.0674, 0.0200, 0.0263, 0.0249, 0.1226,
        0.0164, 0.0075, 0.0789, 0.0131, 0.0267, 0.0147, 0.0112, 0.0585, 0.0121,
        0.0650, 0.0058, 0.0208, 0.0078, 0.0133, 0.0203, 0.1204, 0.0469, 0.0126])
label (actual next character): 1
probability assigned by the net to the the correct character: 0.07367684692144394
log likelihood: -2.6080667972564697
negative log likelihood: 2.6080667972564697

--------

bigram example 5: a. (indexes 1,0)
input to the neural net: 1
output probabilities from the neural net: tensor([0.0150, 0.0086, 0.0396, 0.0100, 0.0606, 0.0308, 0.1084, 0.0131, 0.0125,
        0.0048, 0.1024, 0.0086, 0.0988, 0.0112, 0.0232, 0.0207, 0.0408, 0.0078,
        0.0899, 0.0531, 0.0463, 0.0309, 0.0051, 0.0329, 0.0654, 0.0503, 0.0091])
label (actual next character): 0
probability assigned by the net to the the correct character: 0.01497753243893385
log likelihood: -4.2012038230896
negative log likelihood: 4.2012038230896
=========
average negative log likelihood, i.e. loss = 3.7693049907684326

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$.

In [42]:
xs
Out[42]:
tensor([ 0,  5, 13, 13,  1])
In [43]:
ys
Out[43]:
tensor([ 5, 13, 13,  1,  0])
In [44]:
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
In [45]:
#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
In [46]:
probs[0,5], probs[1,13], probs[2,13], probs[3,1], probs[4,0]
Out[46]:
(tensor(0.0123, grad_fn=<SelectBackward0>),
 tensor(0.0181, grad_fn=<SelectBackward0>),
 tensor(0.0267, grad_fn=<SelectBackward0>),
 tensor(0.0737, grad_fn=<SelectBackward0>),
 tensor(0.0150, grad_fn=<SelectBackward0>))
In [47]:
torch.arange(5)
Out[47]:
tensor([0, 1, 2, 3, 4])
In [48]:
loss = -probs[torch.arange(5), ys].log().mean()
loss
Out[48]:
tensor(3.7693, grad_fn=<NegBackward0>)

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 .e label 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.

In [49]:
#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
In [50]:
W.grad
Out[50]:
tensor([[ 0.0121,  0.0020,  0.0025,  0.0008,  0.0034, -0.1975,  0.0005,  0.0046,
          0.0027,  0.0063,  0.0016,  0.0056,  0.0018,  0.0016,  0.0100,  0.0476,
          0.0121,  0.0005,  0.0050,  0.0011,  0.0068,  0.0022,  0.0006,  0.0040,
          0.0024,  0.0307,  0.0292],
        [-0.1970,  0.0017,  0.0079,  0.0020,  0.0121,  0.0062,  0.0217,  0.0026,
          0.0025,  0.0010,  0.0205,  0.0017,  0.0198,  0.0022,  0.0046,  0.0041,
          0.0082,  0.0016,  0.0180,  0.0106,  0.0093,  0.0062,  0.0010,  0.0066,
          0.0131,  0.0101,  0.0018],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0058,  0.0159,  0.0050,  0.0104,  0.0398,  0.0058,  0.0019,  0.0067,
          0.0019,  0.0060,  0.0140,  0.0046,  0.0023, -0.1964,  0.0022,  0.0063,
          0.0058,  0.0009,  0.0183,  0.0043,  0.0097,  0.0060,  0.0100,  0.0005,
          0.0024,  0.0004,  0.0094],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0125, -0.1705,  0.0194,  0.0133,  0.0270,  0.0080,  0.0105,  0.0100,
          0.0490,  0.0066,  0.0030,  0.0316,  0.0052, -0.1893,  0.0059,  0.0045,
          0.0234,  0.0049,  0.0260,  0.0023,  0.0083,  0.0031,  0.0053,  0.0081,
          0.0482,  0.0187,  0.0051],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,
          0.0000,  0.0000,  0.0000]])
In [51]:
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.

In [52]:
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}")
step 1, loss: 3.7492
step 2, loss: 3.7292
step 3, loss: 3.7092
step 4, loss: 3.6892
step 5, loss: 3.6693
step 6, loss: 3.6494
step 7, loss: 3.6296
step 8, loss: 3.6098
step 9, loss: 3.5900
step 10, loss: 3.5703

Training on every bigram

Every bigram in the dataset, the same $\sum_w (|w| + 1)$ counted earlier, and W reset to the seeded draw.

In [53]:
# 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)
number of examples: 
 228146

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.

In [54]:
(W**2).mean()
Out[54]:
tensor(0.9665, grad_fn=<MeanBackward0>)
In [55]:
# 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
3.76861834526062
3.3788065910339355
3.161090850830078
3.0271859169006348
2.9344842433929443
2.867231607437134
2.8166542053222656
2.777146339416504
2.7452542781829834
2.7188305854797363
2.696505546569824
2.6773719787597656
2.6608054637908936
2.6463515758514404
2.633665084838867
2.622471570968628
2.6125476360321045
2.6037068367004395
2.595794439315796
2.5886809825897217
2.582256317138672
2.5764293670654297
2.5711236000061035
2.566272735595703
2.5618226528167725
2.5577261447906494
2.5539445877075195
2.550442695617676
2.5471930503845215
2.5441696643829346
2.5413525104522705
2.538722038269043
2.536262035369873
2.5339579582214355
2.531797409057617
2.5297679901123047
2.527860164642334
2.526063919067383
2.5243709087371826
2.522773265838623
2.52126407623291
2.519836664199829
2.5184855461120605
2.517204999923706
2.515990972518921
2.5148372650146484
2.5137410163879395
2.512698173522949
2.511704444885254
2.5107579231262207
2.509855031967163
2.5089924335479736
2.5081682205200195
2.5073797702789307
2.5066258907318115
2.5059030055999756
2.5052106380462646
2.5045459270477295
2.5039076805114746
2.503295421600342
2.5027060508728027
2.5021398067474365
2.501594305038452
2.5010693073272705
2.500563383102417
2.500075101852417
2.4996049404144287
2.4991507530212402
2.4987120628356934
2.49828839302063
2.4978790283203125
2.4974827766418457
2.4970996379852295
2.4967291355133057
2.496370315551758
2.496022939682007
2.4956860542297363
2.4953596591949463
2.4950432777404785
2.4947361946105957
2.494438886642456
2.494149684906006
2.4938690662384033
2.4935967922210693
2.4933323860168457
2.493075132369995
2.4928252696990967
2.492582321166992
2.4923462867736816
2.492116689682007
2.4918930530548096
2.491675853729248
2.491464614868164
2.491258382797241
2.491058349609375
2.4908626079559326
2.4906723499298096
2.4904870986938477
2.4903063774108887
2.4901304244995117

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.

In [56]:
# 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))
cexze.
momasurailezityha.
konimittain.
llayn.
ka.