Earth 1

Library of human understanding

Computer Science

From one switch to machines that write.

Every computer, from a phone to a data-centre full of AI chips, is built from the same idea: a switch that is either on or off, wired to other switches so that patterns of on and off follow rules. Everything else is a question of how many switches, how they are arranged, and how fast data can be brought to them.

How a computer computes

Before comparing chips, it helps to see what every chip shares.

Bits, transistors and logic gates

A bit is the smallest piece of information: a yes or a no, written 1 or 0. Claude Shannon showed in 1948 that any message, a picture, a song, this sentence, can be measured and sent as bits.

A transistor is a switch with no moving parts. A small voltage on one terminal lets current flow between the other two, or stops it. A modern chip holds tens of billions of them, each only a few tens of atoms across in its smallest features.

Wire a few transistors together and you get a logic gate: AND outputs 1 only if both inputs are 1, OR if either is, NOT flips its input. One gate, NAND (not-and), is enough on its own to build every other gate, and so every circuit. Chain gates into an adder and the machine can do arithmetic; add a loop that remembers its output and it can store a bit. Arithmetic plus memory is a computer.

Information in bits

  • H: how many bits you need
  • N: how many equally likely possibilities there are
  • log₂: how many times you must halve N to reach 1. Eight choices need 3 bits, because 2 × 2 × 2 = 8.

The stored program and the clock

In 1936 Alan Turing described a machine that could carry out any calculation that can be written as steps, if you gave it the steps as data. In 1945 John von Neumann's report on the EDVAC laid out the practical form almost every computer still follows: the program and the data live in the same memory, and a processor repeatedly fetches an instruction, decodes what it means, executes it, and moves on.

A clock keeps all of this in step. Each tick, signals move one stage further through the circuits. A 4 GHz processor ticks four billion times a second, so one tick lasts a quarter of a nanosecond, in which light itself travels only about 7.5 centimetres.

How long a program takes

  • t: time to run the program, in seconds
  • N_instr: how many instructions the program executes
  • CPI: average clock ticks each instruction needs (modern chips get this below 1 by doing several at once)
  • f: clock frequency, ticks per second

The memory wall

Since the 1980s processors have become faster much more quickly than memory has. A processor can now do hundreds of operations in the time it takes to fetch one number from main memory. This gap is called the memory wall, and almost every design decision in the three chips below is a different answer to it.

The usual answer is a ladder of memories: tiny and fast close to the arithmetic, huge and slow far away. The lab below shows the ladder with times stretched so that one L1 cache read takes one second.

  • Register

    0.3 ns

    a few kilobytes

    If L1 took 1 second: 0.3 seconds.

  • L1 cache

    1 ns

    tens of kilobytes per core

    If L1 took 1 second: 1 second.

  • L2 cache

    4 ns

    about 1–2 megabytes per core

    If L1 took 1 second: 4 seconds.

  • L3 cache

    15 ns

    tens of megabytes, shared

    If L1 took 1 second: 15 seconds.

  • Main memory (DRAM)

    90 ns

    gigabytes

    If L1 took 1 second: 2 minutes.

  • Solid-state drive

    50 µs

    terabytes

    If L1 took 1 second: 13.9 hours.

  • Hard disk

    5 ms

    terabytes

    If L1 took 1 second: 1.9 months.

The bar uses a log scale: each step covers a much larger memory delay than the one before it.

The CPU: a few brilliant workers

The central processing unit runs the operating system, the browser, the database and almost every program you have used. Its job is to finish one stream of instructions as quickly as possible, whatever that stream contains.

Inside a core

A core is one complete processor. A phone or laptop has roughly 6 to 16, a large server chip can have well over a hundred. Each core is big and clever, because most of its transistors are spent not on arithmetic but on guessing and organising.

Pipelining splits each instruction into stages, like a car factory line, so that a new instruction can start every tick while earlier ones finish. Superscalar cores run several pipelines side by side. Out-of-order execution looks ahead in the program and runs any instruction whose inputs are ready, then puts the results back in order. Branch prediction guesses which way each if-statement will go before it is known, and is right well over 95% of the time on typical code; a wrong guess throws away the work and costs a dozen or more ticks.

Caches (L1, L2, L3) keep recently used data close by, because programs tend to reuse the same data and to read neighbouring addresses. SIMD units (on x86 called SSE and AVX, on Arm called NEON and SVE) apply one instruction to a short row of numbers at once, a small taste of what a GPU does at huge scale.

Built for latency

All that machinery serves one goal: low latency, meaning the time until a single task is done. It is why a CPU is good at code full of decisions, such as compilers, web servers, games logic and spreadsheets, where the next step depends on the last.

The cost is that only a small share of the chip actually does arithmetic. When the work is a million identical, independent sums, a few brilliant workers are the wrong tool, and the limit is set by how much of the job can be split up.

Amdahl's law

  • S: how many times faster the whole job gets
  • p: the fraction of the job that can run in parallel
  • n: how many workers (cores) share that parallel part
  • 1 − p: the part that must run one step at a time. If even 5% is serial, no number of cores can make the job more than 20 times faster.

The GPU: an army of simple workers

The graphics processing unit was built to colour millions of pixels sixty or more times a second. Each pixel can be worked out independently of the others, so instead of a few clever cores a GPU has thousands of simple ones doing the same thing to different data.

Thousands of lanes in lock-step

An NVIDIA GPU is made of streaming multiprocessors. Each runs threads in groups of 32, called warps, that execute the same instruction at the same moment on different numbers. This is SIMT: single instruction, multiple threads. AMD's equivalent group is the wavefront. A large GPU keeps well over a hundred thousand threads in flight at once.

GPUs barely try to guess or reorder. Instead, when one warp is waiting for memory, the hardware simply switches to another warp that is ready, in a single tick. With enough work queued, the arithmetic units never sit idle. If threads in one warp take different sides of an if-statement, the two sides run one after the other with half the lanes switched off, which is why branchy code runs poorly on a GPU.

The result is throughput rather than latency: each individual task finishes no sooner, often later, but vastly more tasks finish per second. The race below shows the difference.

CPU · 8 cores

Tick 0

GPU · 512 lanes

Tick 0
Toy numbers: each CPU core is 4 times faster than each GPU lane, but the GPU has 64 times as many.

From pixels to neural networks

In 2007 NVIDIA released CUDA, which let programmers use the GPU for any parallel arithmetic, not just graphics. In 2012 a neural network called AlexNet, trained on two consumer NVIDIA GTX 580 graphics cards, won the ImageNet image-recognition contest by a wide margin, and deep learning moved onto GPUs almost overnight.

Neural networks are mostly matrix multiplication, so from the Volta generation in 2017 NVIDIA added tensor cores: units that multiply and add whole small blocks of a matrix in one instruction, in reduced precision such as 16-bit or 8-bit numbers. Feeding them needs enormous memory bandwidth, so data-centre GPUs sit beside stacks of high-bandwidth memory (HBM): an H100 reads about 3.35 terabytes per second, roughly forty times a typical laptop's main memory. Fast links such as NVLink tie many GPUs into one machine.

Matrix multiplication

  • A, B: the two grids of numbers being multiplied
  • C_ij: the number in row i, column j of the answer
  • Σ (sum over k): walk along row i of A and down column j of B, multiply the pairs, add them all up
  • Every C_ij can be computed independently of the others, which is exactly the kind of work a GPU loves. Multiplying an M × K grid by a K × N grid costs 2·M·N·K operations (one multiply and one add each time).

The TPU: a chip shaped like the maths

Google's Tensor Processing Unit goes one step further than the GPU: it gives up being general and is built around the one operation neural networks need most, multiplying matrices. It is an ASIC, an application-specific integrated circuit.

The systolic array

In 1978 H. T. Kung and Charles Leiserson proposed the systolic array, named after the heartbeat that pumps blood: a grid of tiny cells, each of which, every tick, multiplies two numbers, adds the result to a running total and passes data to its neighbour. Data is read from memory once and then reused as it flows across the whole grid, instead of being fetched again for every multiplication.

In a TPU's matrix unit the weights of the network are loaded into the grid and stay put. The inputs flow in from the left, one diagonal wave per tick, and the partial sums flow downward, picking up one more product at each cell, until finished answers drop out of the bottom. The first TPU's grid was 256 × 256, which is 65,536 multiply-adds every tick. Step through a small one below.

Fixed weights stay in place. Inputs move right; partial sums move down.

W[0,0]

1

x: ·

Σ: ·

W[0,1]

0

x: ·

Σ: ·

W[0,2]

2

x: ·

Σ: ·

W[1,0]

3

x: ·

Σ: ·

W[1,1]

1

x: ·

Σ: ·

W[1,2]

0

x: ·

Σ: ·

W[2,0]

0

x: ·

Σ: ·

W[2,1]

2

x: ·

Σ: ·

W[2,2]

1

x: ·

Σ: ·

Tick 0 of 7

Outputs leaving the array

·
·
·
·
·
·
·
·
·
Each cell multiplies the passing input by its fixed weight and adds the partial sum flowing down from above.

What the TPU gives up, and gains

Google had the first TPU running in its data centres in 2015 and announced it in 2016. It used 8-bit integers and only ran trained networks. Later generations train them too, with several 128 × 128 matrix units per chip and a number format Google Brain devised called bfloat16, which keeps the range of a 32-bit float (8 exponent bits) but only 7 bits of precision. Neural networks tolerate the lost precision; the chip saves half the memory and far more than half the silicon per multiplier.

With no graphics hardware, little branch logic and a simpler cache, more of the chip goes on arithmetic and less energy is spent moving data. TPUs are joined into pods by their own chip-to-chip links: a TPU v4 pod connects 4,096 chips. The trade-off is flexibility. A TPU is superb at large, regular matrix work, mainly through Google's XLA compiler (used by JAX, TensorFlow and PyTorch), and poor at anything else.

The same idea now sits in phones and laptops as the neural processing unit (NPU), such as Apple's Neural Engine, first shipped in 2017.

The roofline

  • P: operations per second you actually get
  • P_peak: the most the arithmetic units could do if never kept waiting
  • B: memory bandwidth, bytes per second
  • I: arithmetic intensity, operations done per byte fetched. Big matrix multiplications have high I and hit the compute roof; reading each number once and using it once has low I and is limited by memory. Systolic arrays exist to raise I.

Four processor architectures

Speed vsPurposeCPUGPUTPUSpecialized

CPU

Strength: General purpose, versatile

Tradeoff: Slower at specialized tasks

GPU

Strength: Massive parallelism, fast math

Tradeoff: Memory bandwidth limited

TPU

Strength: ML-optimized, extreme speed

Tradeoff: Fixed hardware, not general

Specialized

Strength: Domain-specific peak performance

Tradeoff: Narrow use case only

All modern computing uses a mix. The choice depends on your problem: general-purpose work favors CPUs; parallel math favors GPUs; AI/ML uses TPUs; signal processing uses specialized chips.

How large language models work

A large language model (LLM) is a very large neural network trained to do one thing: given some text, predict what comes next. Everything it appears to do, answering, translating, writing code, comes from doing that one thing extremely well, one small piece of text at a time.

Tokens and embeddings

The model does not see letters or words but tokens: common chunks of text found by an algorithm such as byte-pair encoding. 'the' is one token, 'unbelievable' might be three. In English a token averages about three-quarters of a word. A vocabulary has tens of thousands to a couple of hundred thousand tokens, each with an ID number.

Each token ID is swapped for an embedding: a list of a few thousand numbers (12,288 in GPT-3) that the model learns during training. Tokens used in similar ways end up with similar lists, so meaning becomes a direction in a space of thousands of dimensions. Information about each token's position in the text is mixed in, today usually by rotating pairs of those numbers by an angle that depends on the position (rotary embeddings).

Attention: every word looks back at the others

The Transformer, introduced by a Google team in the 2017 paper 'Attention Is All You Need', is the design behind every major LLM. Its key step is attention. Each token makes three vectors from its embedding: a query (what am I looking for?), a key (what do I contain?) and a value (what will I pass on?).

Each token compares its query with the keys of every earlier token. Close matches get high scores, softmax turns the scores into weights that add up to 1, and the token takes the weighted blend of their values. That is how 'it' in 'the animal didn't cross the street because it was too tired' can pull in information from 'animal'. In a language model each token may look only backward, never at words not yet written.

A model runs many attention heads side by side (96 in GPT-3), each free to learn a different kind of relationship. Try a toy version below.

Scaled dot-product attention

  • Q: the queries, one row per token
  • K: the keys; QKᵀ scores every query against every key with a dot product (multiply matching entries and add)
  • √d_k: the square root of the key length; dividing by it stops scores from growing too large as vectors get longer
  • softmax: turns each row of scores into positive weights that add up to 1
  • V: the values; the weights decide how much of each value each token takes

Choose a token to see what it looks back at.

  • The3.8%
  • animal62.6%
  • didn't3.1%
  • cross3.1%
  • the3.1%
  • street14.0%
  • because5.1%
  • it5.1%
  • was0.0%
  • too0.0%
  • tired0.0%
Toy scores chosen by hand to show the mechanics; a real model learns them, across many heads at once.

Layers, the feed-forward network and the residual stream

After attention, each token's vector goes through a feed-forward network: multiply by a large matrix, apply a simple bend (a nonlinearity such as GELU or SwiGLU), multiply by another matrix. Attention moves information between tokens; the feed-forward step works on each token by itself, and is where much of what the model has learnt about the world appears to be stored.

Attention plus feed-forward makes one layer, or block. Each block adds its output to the vector it received rather than replacing it (a residual connection), so the vector is a running stream that every layer reads from and writes to. Normalisation keeps its numbers in a sensible range. GPT-3 stacks 96 blocks. Almost every operation in a block is a matrix multiplication, which is why this software and the chips above fit together so well.

Some recent models use a mixture of experts: many feed-forward networks per layer, with a small router sending each token to only a few of them, so a model can hold many parameters but use only a fraction for each token.

Predicting the next token

At the top of the stack, the last token's vector is multiplied by one more matrix to give a score, called a logit, for every token in the vocabulary. Softmax turns the scores into probabilities. The model then picks one, appends it to the text, and runs again for the next. Generating a 500-token answer means running the whole network 500 times.

Temperature controls the pick. Near zero, the model almost always takes the most likely token and becomes repetitive and safe; higher, it takes more chances and becomes more varied, and more often wrong. Play with it below.

Softmax with temperature

  • p_i: the probability of choosing token i
  • z_i: the model's raw score (logit) for token i
  • T: temperature. Dividing by a small T exaggerates the gaps between scores; a large T flattens them
  • e^x: the exponential, which makes every score positive; dividing by the sum over all tokens j makes the probabilities add up to 1

The capital of France is

  • Paris96.0%
  • a1.8%
  • the1.1%
  • known0.6%
  • located0.3%
  • beautiful0.2%
  • Lyon0.1%
Toy scores; a real model scores every token in a vocabulary of over a hundred thousand.

Training: learning from trillions of tokens

A new model starts with random numbers in all its matrices, its parameters, and produces nonsense. Pre-training shows it a vast amount of text, trillions of tokens of books, websites and code, and at every position asks it to predict the next token. The loss measures how surprised it was by the real answer.

Backpropagation, popularised by Rumelhart, Hinton and Williams in 1986, works out how much each parameter contributed to the error, all of them at once, by running the chain rule of calculus backwards through the network. Gradient descent then nudges every parameter a little in the direction that would have lowered the loss. Repeat that over trillions of tokens and the parameters come to encode grammar, facts, and patterns of reasoning, because those are what make text predictable.

A pre-trained model only continues text. To make it a helpful assistant it is fine-tuned on examples of good answers, then trained further with human or automated preferences (reinforcement learning from human feedback, popularised by OpenAI's InstructGPT in 2022), and, in newer reasoning models, rewarded for working through problems step by step and reaching checkable right answers.

Cross-entropy loss

  • L: the loss at one position; training minimises its average
  • p_correct: the probability the model gave to the token that really came next
  • −log: zero when the model was certain and right, growing without limit as it gave the right answer less probability

Gradient descent

  • θ (theta): all the model's parameters
  • ∇L (the gradient): for every parameter, which way and how steeply the loss rises; backpropagation computes it
  • η (eta): the learning rate, how big a step to take. In practice an optimiser called Adam adapts the step for each parameter
  • ←: replace the old values with the new ones, then repeat for the next batch

Training compute

  • C: total arithmetic operations needed to train
  • N: number of parameters
  • D: number of training tokens
  • 6: about 2 operations per parameter per token for the forward pass and 4 for the backward pass. A 70-billion-parameter model on 15 trillion tokens needs about 6 × 10²⁴ operations, months of work for thousands of chips. DeepMind's Chinchilla study (2022) found the best use of a fixed budget is roughly 20 tokens per parameter.

Running a model: why memory speed sets the pace

Answering a prompt has two phases. In prefill the model reads your whole prompt at once; all its tokens go through each layer together, so the work is big matrix multiplications and the chip's arithmetic is the limit. In decode it writes the answer one token at a time, and to make each token it must read every one of its parameters from memory again. With one user, the chip's arithmetic mostly waits and the speed is set by memory bandwidth: the roofline above, at low intensity.

To avoid redoing work, the keys and values of every earlier token are kept in a KV cache, which grows with the conversation and is why long contexts cost memory. Serving many users at once (batching) lets one read of the weights serve many tokens, raising intensity. Quantisation stores weights in 8 or 4 bits instead of 16, so there is less to read. Models too big for one chip are split across many: by layer (pipeline parallelism) or by slicing each matrix (tensor parallelism). Estimate the speed limit yourself below.

This is also why a model can be confidently wrong. It produces the most plausible continuation, not a checked fact, and it knows only what was in its training data and what is in the text in front of it.

Decode speed limit (one user)

  • B: memory bandwidth, bytes per second
  • N: number of parameters
  • b: bytes per parameter: 2 at 16-bit, 1 at 8-bit, 0.5 at 4-bit
  • N × b: the size of the weights, all of which are read once per token. Each token also costs about 2N arithmetic operations.
Precision
Hardware
Weight size
140 GB
Chips needed to hold the weights
2
Maximum decode speed
48 tokens/s

Ideal: chips read their share in parallel.

Operations per token
140 billion
Upper bound for one user; ignores the KV cache, communication between chips and batching.

CPU, GPU, and TPU in action

CPU, GPU, and TPU: How they multiply differently

Computing a 4-element matrix multiply (r = a · b) takes different paths on each processor. CPU does one element per tick. GPU does all 4 in parallel with SIMT. TPU fills a systolic grid where data flows and computation happens at each cell.

CPU

CPU: One multiply-add per cycle

t=0
✓
r0 = a[0] × b[0] + r0
t=1
waiting
t=2
waiting
t=3
waiting
GPU

GPU: 4 threads in SIMT (same instruction, different data)

t=0
0
1
2
3
all 4 threads: r += a[i] × b[i]
t=1
0
1
2
3
all 4 threads: r += a[i] × b[i]
t=2
0
1
2
3
all 4 threads: r += a[i] × b[i]
t=3
0
1
2
3
all 4 threads: r += a[i] × b[i]
TPU

TPU: 4×4 systolic array, data flows through

t=0
×
1
2
3
each cell does one mul-add
t=1
0
1
2
3
each cell does one mul-add
t=2
0
1
2
3
each cell does one mul-add
t=3
0
1
2
3
each cell does one mul-add
t=4
0
1
2
3
each cell does one mul-add
t=5
0
1
2
3
each cell does one mul-add

Timeline:

  • t=0–3: CPU computes one element per tick
  • t=0: GPU and TPU both start, but GPU is faster on this task
  • t=0–5: TPU fills the systolic array
  • Throughput: CPU = 1/tick, GPU = 4/tick, TPU = 4/tick (but fills, then 4 every tick)
Why each design

CPU (scalar): Built for latency on one task. Great when work is branchy or data dependent.

GPU (SIMT): Thousands of threads doing the same thing on different data. High throughput. Poor on branchy code (threads diverge).

TPU (systolic): Designed around matrix multiply. Data flows in, is reused as it crosses the grid. Highest throughput for large, regular work.

Timeline

  1. 1936

    Alan Turing describes a universal machine that can carry out any step-by-step calculation.

  2. 1945

    John von Neumann's EDVAC report sets out the stored-program computer. John von Neumann

  3. 1947

    Bardeen, Brattain and Shockley build the first transistor at Bell Labs.

  4. 1948

    Claude Shannon's 'A Mathematical Theory of Communication' makes the bit the unit of information.

  5. 1958–59

    Jack Kilby and Robert Noyce independently invent the integrated circuit.

  6. 1965

    Gordon Moore observes that the number of transistors on a chip doubles at a steady rate.

  7. 1971

    Intel's 4004, about 2,300 transistors, is the first commercial single-chip microprocessor.

  8. 1978

    H. T. Kung and Charles Leiserson propose systolic arrays.

  9. 1986

    Rumelhart, Hinton and Williams popularise backpropagation for training neural networks.

  10. 1999

    NVIDIA markets the GeForce 256 as the first GPU.

  11. 2007

    NVIDIA releases CUDA, opening GPUs to general-purpose computing.

  12. 2012

    AlexNet, trained on two GTX 580 GPUs, wins ImageNet and starts the deep-learning boom.

  13. 2015

    Google's first TPU goes into service in its data centres; it is announced in 2016.

  14. 2017

    'Attention Is All You Need' introduces the Transformer; NVIDIA's Volta GPUs add tensor cores.

  15. 2020

    OpenAI's GPT-3, with 175 billion parameters, shows abilities emerging from scale alone.

  16. 2022

    DeepMind's Chinchilla study rebalances model size against data; ChatGPT launches in November.

  17. 2023

    Openly downloadable models such as Meta's Llama let anyone run an LLM on their own hardware.

Build a Computer

Build a Computer

Start with logic gates, build an ALU, then assemble a simple CPU and run a program through it.

What is a logic gate?

A logic gate takes one or more binary inputs (0 or 1) and produces an output following a simple rule. Every circuit in every computer is made by wiring these gates together.

Choose a gate
AND gate

Outputs 1 only if both inputs are 1

Output
0