Language: Tokens to Next Word

Timeline, 1822–2026
  1. 1822◆Babbage proposes the Difference Engine
  2. 1843◆Lovelace publishes the first program, for the Analytical Engine
  3. 1936◆Turing: a machine that can imitate any other
  4. 1937Shannon: relay circuits do Boolean logic
  5. 1941◆Zuse’s Z3, a programmable relay computer
  6. 1943McCulloch and Pitts: a neuron as a switch
  7. 1946ENIAC: 17,468 tubes, 150 kW
  8. 1947The transistor, Bell Labs
  9. 1958Rosenblatt’s perceptron
  10. 1959The MOSFET (Atalla and Kahng) and the planar chip
  11. 1965Moore’s observation
  12. 1969Minsky and Papert’s Perceptrons
  13. 1971◆Intel 4004, made for Busicom of Japan
  14. 1974Dennard’s scaling rules
  15. 1976Cray-1
  16. 1986Backpropagation popularised
  17. 1989LeCun’s convolutional network reads zip codes
  18. 1997◆LSTM (Hochreiter and Schmidhuber)
  19. ~2005Dennard scaling ends; clock speeds stall
  20. 2007CUDA lets GPUs run general code
  21. 2009ImageNet
  22. 2011◆K computer tops the TOP500
  23. 2012◆AlexNet, trained on two gaming GPUs
  24. 2017“Attention Is All You Need”
  25. 2020Scaling laws; GPT-3; Fugaku tops the TOP500
  26. 2022Chinchilla; H100; ChatGPT
  27. 2024100,000-GPU clusters; a 1,500 MW data-centre load drops off the Virginia grid
  28. 2025◆IEA: data centres used 415 TWh in 2024

In brief. How a transformer turns “how big is the model?” into “how many operations does an answer cost?”: about two per active parameter for each token, plus attention that grows with the context.

The surprise. Meta’s Llama 3 has a vocabulary of about 128,000 tokens and was trained on about 15 trillion of them.

A transformer answering a question does one job over and over: given the tokens so far, score every token that could come next, and pick. The arithmetic for one token is roughly twice the number of active parameters, plus an attention term that grows with the length of the context — a rule of thumb that turns “how big is the model?” into “how many operations does an answer cost?”.1 This page builds up to that rule, from a small filter reused everywhere to attention as a soft lookup.

It follows A model. Together they feed the Act 1 meter’s unit: Wh per answer, derived from operations per token.

  1. 1One small filter, used everywhere
  2. 2Learning the noise
  3. 3Reading one word at a time
  4. 4Attention: a lookup you can blur
  5. 5Predicting the next word
  6. 6What changed, and what did not
  7. Final words

1One small filter, used everywhere

Background. This section and the next matter to the energy question only through what came after them: re-using one small set of weights everywhere saves arithmetic, and fitting noise is why models need ever more data (The data). For the thread that leads to the meter, skip to attention.

A photograph is a grid of numbers, one per pixel. A network could connect every pixel to every neuron of its first layer, but that wastes effort: an edge is an edge wherever it appears, and a network that learns to see one in the top-left corner has learned nothing about the bottom-right. In 1959 David Hubel and Torsten Wiesel found that cells in a cat’s visual cortex each respond to edges at one angle in one small patch of the visual field, with many such cells tiling the whole field.2 Kunihiko Fukushima in Tokyo built that layout into a network, the neocognitron, in 1980.3

The modern form is the convolution: a small square of weights, the filter, slid across the whole picture. At each position it multiplies the nine pixels under it by its nine weights and adds them up. Slide the violet window below; on the right, blue marks a strong positive answer and orange a strong negative one.

Model A 14 by 14 pixel drawing of a seven and a 3 by 3 filter. Each square on the right is the sum of the nine products when the filter sits at the matching place on the left. The edge filters are fixed by hand here; in a trained network all the filters are learned weights.

The horizontal-edge filter lights up along the top bar of the seven and responds only weakly to its slanted stroke. The vertical one does roughly the opposite. A real network learns dozens of filters in its first layer, then applies more filters to their outputs, building edges into corners, corners into shapes and shapes into objects. Because each filter is reused everywhere, it has very few weights to learn, and so it needs far fewer examples.

In 1989 Yann LeCun and colleagues at AT&T Bell Laboratories trained such a network by backpropagation to read handwritten zip codes from US mail.4 Its descendant, LeNet-5, read cheques in banks in the 1990s.5 The network that won ImageNet in 2012, in the essay, was the same design, much larger, trained on far more data and on graphics cards.

The maths: convolution

For an image I and a k × k filter K, the output at position (i, j) is

O(i, j) = Σₐ Σ_b K(a, b) · I(i + a, j + b).

(Strictly that is cross-correlation; the flip that turns it into a mathematical convolution makes no difference once K is learned.) An n × n image gives (n − k + 1)² outputs from just k² weights. Here that is 144 outputs from 9 weights, against 196 × 144 = 28,224 weights for a fully connected layer of the same size.

2Learning the noise

A network with enough weights can fit almost any set of examples exactly, including their accidents. That is a danger, not a success. What matters is how well it does on examples it has never seen. The figure fits curves of increasing wiggliness through a handful of noisy points. The points come from a smooth wave (dashed) plus random scatter. On the right, the error on the training points is drawn in black and the error on new data in orange.

Model Training points drawn from a sine wave (dashed) plus random noise, fitted by least squares with polynomials of degree 0 up to one less than the number of points (at most 14), where the curve passes through every point exactly; the grey zone beyond that is left empty. The error chart gives the average (root-mean-square) error of every fit on the training points and on 300 fresh points from the same source. The noise itself has a typical size of 0.25, so no fit can do better than that on new points.

Stiff curves miss the wave. As the curve gets wigglier, the error on the training points keeps falling, and with enough wiggle it threads through every point exactly. But the error on fresh points falls, bottoms out, then shoots up: the curve has started memorising the scatter. This is overfitting. Add training points and the bottom of the curve moves right: more data lets you afford a more flexible model. That is the trade at the heart of machine learning, and the reason ImageNet’s millions of labelled photos mattered as much as the network.

The textbook story, a U-shaped curve with a sweet spot, held for decades.6 Modern networks complicate it. They have far more weights than training examples and still generalise well, and in 2019 Mikhail Belkin and colleagues showed that, past the point where a model can fit its data exactly, test error can fall again as the model grows: “double descent”.7 Why very large networks generalise as well as they do is still an active research question. The figure stops at the degree where the curve first passes through every point, so it shows only the classical half of that story.

The maths: bias and variance

For a fit f̂ trained on random data from y = f(x) + ε with noise variance σ², the expected squared error at a new point splits into three parts:

E[(y − f̂(x))²] = (f(x) − E f̂(x))² + Var f̂(x) + σ².

Those are bias², variance and noise. Stiff models have high bias; wiggly ones fitted to few points have high variance. More data shrinks the variance, which is why the best degree in the figure rises as you add points. The fits use orthogonal (Legendre) polynomials and a tiny ridge penalty, 10⁻⁶, so that the arithmetic stays stable.

3Reading one word at a time

Language arrives in order, and meaning depends on words far apart. In “the keys that the man who lives next door left on the bus were found”, the verb is “were” because of “keys”, with eleven words in between. From the 1990s through the 2010s the main way to handle this was a recurrent network. It reads one word at a time and carries a fixed-size memory forward, updating it with each word. Below, the bars show how much of each word is still in that memory.8

Model A sentence read left to right through a memory that keeps a fixed fraction of what it held at each step. The bars show how much of each word survives to the current position; the blue bar is the subject, “keys”. The gate setting lets the memory hold on to the subject while the rest fades, the idea behind the LSTM. Real networks store learned vectors, not single fractions.

Two things go wrong. Each update blends the new word into the memory, so old words fade geometrically: keep 80% per word and, twelve words on, less than a tenth of “keys” is left. In training the same thing happens in reverse, because the blame passed backwards shrinks at every step, so the network barely learns from long-range links. Sepp Hochreiter analysed this “vanishing gradient” in his 1991 diploma thesis in Munich.9 In 1997 he and Jürgen Schmidhuber proposed the long short-term memory, or LSTM. It has learned gates that decide what to write into the memory and what to read out, so it can hold on to “keys” until it is needed; a third gate, deciding what to forget, was added in 2000.10 LSTMs powered much of the speech recognition and machine translation of the 2010s.

The second problem did not go away. Word 14 cannot be processed until word 13 is done, and word 13 waits for word 12. However many processors you have, a sentence takes as many steps as it has words. The essay showed why that is fatal on hardware built from thousands of slow hands.

The maths: a recurrent step, and why its gradient vanishes

A simple recurrent network updates a memory vector h with each input xₜ:

hₜ = tanh(W hₜ₋₁ + U xₜ + b).

The influence of h₂ (after “keys”) on h₁₄ (at “were”) is a product of twelve Jacobians, each W multiplied by a tanh slope below 1. If their size is below 1 the product shrinks exponentially (vanishing); if it is above 1 it blows up. An LSTM keeps a separate cell state cₜ = fₜ ⊙ cₜ₋₁ + iₜ ⊙ c̃ₜ with a learned “forget gate” fₜ. When fₜ ≈ 1 the cell is copied forward almost unchanged, and so is its gradient.

4Attention: a lookup you can blur

In 2014 Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio gave a translation network a way to look back. Instead of squeezing a whole sentence into one memory, at each output word it could glance at every input word and choose which to draw on.11 In 2017 a team mostly at Google went further and dropped the step-by-step memory entirely. Their transformer is built from that glance alone, which they called attention.12

Attention works like a lookup table, but blurred. Every word carries a key, a short list of numbers saying what kind of thing it is, here just two: how much of a creature it is and how much of a place. A word that needs information sends out a query saying what it is looking for. The query is compared with the keys, and each match decides how much that word contributes. In “the tired cat sat on the mat because it”, “it” is looking for a creature: “cat” matches best, and “tired” adds to it. A model trained to predict the next word must not peek at the words it is predicting, so each word may only look at itself and the words before it, a rule called the causal mask.12

Model Two-number keys for each word, set by hand to show the idea, drawn as grey arrows on the compass; the yellow arrow is the selected word’s query. Each bar is the softmax of the query’s dot product with that word’s key, taken over the selected word and the words before it; later words are greyed out by the causal mask. A real transformer learns keys and queries with hundreds of numbers each, and runs dozens of such lookups side by side in every layer.
Look inside: embed → attention → MLP → unembed

A transformer is four stages in a row. Tokens become vectors (a table lookup, almost free), look at each other, pass through a feed-forward MLP, and become next-token odds. Every weight costs two FLOPs per token, so at short context the MLP, which holds most of the weights, dominates. Attention also compares each token with every earlier one, and that part grows with the context: past about 100,000 tokens it costs more than all the weights together.

Model Forward-pass FLOPs per token for the Llama 3 70B shape (80 layers, width 8,192, feed-forward 28,672, 8 key–value heads, vocabulary 128,256),13 counted as in Kaplan et al. 2020, Table 1: two per weight, plus 2 × layers × context × width for the attention scores, averaged over a context of that length. Sharing key–value heads shrinks the cache, not this attention arithmetic.1

Point the query towards “a creature” and the bar over “cat” grows; swing it up towards “a place” and “mat” takes over. Shorten the arrow and the attention spreads out evenly; lengthen it and it snaps onto one word. Each word then takes in a weighted mix of the other words’ information, its values, and so comes out of the layer knowing something about its context. “It” leaves knowing it means the cat.

Nothing in this waits for anything else. Every word’s query can be compared with the keys of all the words before it at the same moment, which on a GPU is one large multiplication of two tables of numbers, exactly the arithmetic it is built for. Distance does not matter either: the first word is as easy to reach from the fourteenth as the thirteenth is. A transformer stacks many layers of attention, each followed by a feed-forward network applied to every word separately, which holds two-thirds or more of the layer’s weights. Nearly every large language model since 2018, from GPT and BERT to Llama, is built this way.

The maths: scaled dot-product attention

Stack the queries, keys and values of all n words into matrices Q, K (n × d) and V. Then

Attention(Q, K, V) = softmax(Q Kᵀ / √d) V,

where softmax turns each row of scores into weights that are positive and sum to 1. In a language model the scores of later words are set to −∞ first, the causal mask, so their weights are 0. Dividing by √d keeps the scores from growing with the number of dimensions; in the figure the arrow’s length plays that role, as a sharpness setting. Q, K and V are each the word vectors multiplied by a learned matrix. The cost grows as n² · d, every word against every word, which is why long contexts are expensive.

5Predicting the next word

What do you train such a network to do? The answer that won is almost embarrassingly simple: show it text and ask it to predict the next word. Every sentence ever written is then a free training example, with no labelling needed, and getting good at the task turns out to require learning grammar, facts and some reasoning along the way.

The idea is old. In his 1948 paper founding information theory, Claude Shannon built “approximations to English” by hand. He opened a book at random, found the current word, and wrote down whatever word followed it there.14 The figure below does the same with the first three chapters of Alice’s Adventures in Wonderland, counted in your browser when this page loaded.

Data + Model Next-word probabilities counted from chapters I–III of Lewis Carroll’s Alice’s Adventures in Wonderland (1865; public domain, Project Gutenberg eBook 11), lower-cased and split into words and punctuation.15 “One word” uses only the last word; “two words” uses the last two, and falls back to one when that pair never occurs. This is a counting model, not a neural network.

With one word of look-back the text is locally plausible and globally nonsense, much like Shannon’s. With two words it becomes more Carroll-like, but you will often see it stuck copying the book word for word: most pairs of words occur only once in 6,873, so there is only one choice. Counting cannot fix that. Looking back further needs exponentially more text, because almost every long phrase is new.

A neural network escapes this by generalising instead of counting. It turns each word, or word fragment (a token), into a vector of numbers. Similar words end up with similar vectors, an effect made famous by Tomas Mikolov’s word2vec in 2013.16 A transformer then uses attention over thousands of earlier tokens to produce a probability for every possible next token. The training signal is still the one in this figure: how surprised the model was by the word that actually came next. Meta’s Llama 3, for example, has a vocabulary of about 128,000 tokens and was trained on about 15 trillion of them.13

How much does that buy at toy scale? The next figure puts a real, tiny transformer beside a counting model, and marks the word the book really used in green. Both learned from the same two Alice books with the same last 5% held back, so the passages on the right are text neither has seen.

Data + model Top five guesses for the next word. Left: word-triple counts from both books, falling back to word pairs and single words when a triple is rare (Witten–Bell smoothing). Right: a 2-layer, 4-head transformer with 251,520 weights trained on the same 62,000 words for about three minutes on eight ordinary processor cores; it is the model whose attention is drawn in the essay.17 Words seen fewer than twice in training are not in either model’s vocabulary.

At this size the transformer is barely better, although nobody gave it any counts: it worked out its numbers only by guessing next words. Its first guess is right about as often as the counts’. Its average surprise is lower, which means that on average it gives more probability to the word that really comes next, even when that word is not its first choice. Part of the reason shows above: it spreads probability over words that behave alike, such as head, hands and feet, where counting only knows the exact phrases it saw. Sixty thousand words is very little; the advantage grows with data and size, which is the subject of Scaling.

The maths: n-grams and cross-entropy

A bigram model estimates P(wₜ | wₜ₋₁) = count(wₜ₋₁ wₜ) / count(wₜ₋₁); a trigram model conditions on two words. A neural language model computes P(wₜ | w₁ … wₜ₋₁) with a softmax over the whole vocabulary, and is trained to minimise the average cross-entropy

L = −(1/T) Σₜ log P(wₜ | w<ₜ),

measured in nats or bits per token. That number is the “error” that falls so smoothly with compute in the scaling laws of the essay.

6What changed, and what did not

Line up the ideas and the striking thing is how old most of them are. The neuron as a threshold switch dates from 1943, learning by nudging weights from 1958 and gradients passed backwards from the 1970s. Convolution came in 1980–89, gated memory in 1997, attention in 2014–17. What was missing for most of that time was not an idea but enough examples to learn from and enough cheap arithmetic to do the learning.

Those arrived together in the 2010s: the web’s photos and text on one side, and on the other graphics chips that do thousands of multiply-adds at once. Attention then rearranged the work so that nothing waited for anything else, and the hardware could be kept busy. Every step on this page is the same few operations, repeated on different numbers: multiply, add, compare, nudge.

Final words

One answer is a sequence of next-token predictions. Each token costs about 2 × active-parameters floating-point operations, plus attention’s share, which grows with the context and for a 70-billion-parameter model passes the 2N part at around 100,000 tokens, plus the memory traffic to fetch the weights and the key–value cache. That is the unit the Scaling page multiplies by “how many tokens per task”, and the unit the Act 1 demand slider counts.

For ImageNet, AlexNet and the 2012 turn, see the essay §§10–11. On the long-run meter (the Verdict), this page sets operations per token.

Notes and sources

  1. FLOPs per token ≈ 2 × active parameters for a dense forward pass (the factor of two counts multiply-adds). Mixture-of-experts models activate only a fraction of parameters per token; the same rule uses the active count. Standard rule of thumb in the scaling literature; see Kaplan et al. 2020 and Hoffmann et al. 2022 (Chinchilla). The full count in J. Kaplan et al., “Scaling Laws for Neural Language Models” (2020), §2.1 and Table 1, is Cforward ≈ 2N + 2·nlayer·nctx·dattn. For the Llama 3 70B shape (80 layers, dattn = 8,192) the second term is 1.3 × 10⁶ FLOPs per token of context; it equals 2N ≈ 1.4 × 10¹¹ at about 104,000 tokens, and at 128k it is 1.7 × 10¹¹.
  2. D. H. Hubel and T. N. Wiesel, “Receptive fields of single neurones in the cat’s striate cortex”, Journal of Physiology 148, 574–591 (1959). They shared the 1981 Nobel Prize in Physiology or Medicine.
  3. K. Fukushima, “Neocognitron: a self-organizing neural network model for a mechanism of pattern recognition unaffected by shift in position”, Biological Cybernetics 36, 193–202 (1980).
  4. Y. LeCun, B. Boser, J. S. Denker, D. Henderson, R. E. Howard, W. Hubbard and L. D. Jackel, “Backpropagation applied to handwritten zip code recognition”, Neural Computation 1(4), 541–551 (1989).
  5. Y. LeCun, L. Bottou, Y. Bengio and P. Haffner, “Gradient-based learning applied to document recognition”, Proceedings of the IEEE 86(11), 2278–2324 (1998), which describes LeNet-5 and its use in commercial cheque reading.
  6. S. Geman, E. Bienenstock and R. Doursat, “Neural networks and the bias/variance dilemma”, Neural Computation 4(1), 1–58 (1992).
  7. M. Belkin, D. Hsu, S. Ma and S. Mandal, “Reconciling modern machine-learning practice and the classical bias–variance trade-off”, PNAS 116(32), 15849–15854 (2019).
  8. J. L. Elman, “Finding structure in time”, Cognitive Science 14(2), 179–211 (1990).
  9. S. Hochreiter, Untersuchungen zu dynamischen neuronalen Netzen, diploma thesis, Technische Universität München (1991); see also Y. Bengio, P. Simard and P. Frasconi, “Learning long-term dependencies with gradient descent is difficult”, IEEE Transactions on Neural Networks 5(2), 157–166 (1994).
  10. S. Hochreiter and J. Schmidhuber, “Long short-term memory”, Neural Computation 9(8), 1735–1780 (1997). The forget gate: F. A. Gers, J. Schmidhuber and F. Cummins, “Learning to forget: continual prediction with LSTM”, Neural Computation 12(10), 2451–2471 (2000).
  11. D. Bahdanau, K. Cho and Y. Bengio, “Neural Machine Translation by Jointly Learning to Align and Translate” (2014; ICLR 2015).
  12. A. Vaswani et al., “Attention Is All You Need”, NeurIPS 2017.
  13. Llama Team, AI @ Meta, “The Llama 3 Herd of Models” (2024).
  14. C. E. Shannon, “A mathematical theory of communication”, Bell System Technical Journal 27, 379–423 and 623–656 (1948), section 3, “The series of approximations to English”.
  15. L. Carroll, Alice’s Adventures in Wonderland (1865), Project Gutenberg eBook 11; public domain. Chapters I–III, 6,873 words and punctuation marks after our preprocessing.
  16. T. Mikolov, K. Chen, G. Corrado and J. Dean, “Efficient Estimation of Word Representations in Vector Space” (2013).
  17. Trained for this series (PyTorch on CPU, fixed seed). Data: Lewis Carroll’s two Alice books, Project Gutenberg eBooks #11 and #12 (public domain), the last 5% of each held out; 62,040 training and 3,266 held-out words and punctuation marks; vocabulary 2,318 (7% of held-out words fall outside it). Held-out perplexity: transformer 94, word pairs 105, word triples 111, single words 245. First guess right on 1,336 held-out words that are in the vocabulary and not punctuation: transformer 16.3%, word triples 16.8%. Dropout and training length were chosen from four short runs scored on the held-out text, so the transformer’s figures are slightly flattering. The prompts “from the books” occur in the training text.

Figures marked Data use the cited sources; Data + model combine them with the series’ own arithmetic. Figures marked Model are simplified models built to show a mechanism; their assumptions are listed under ⓘ data.