Primer llms math

Transformer vs. neural network

People ask what the difference is between a transformer and a neural network, and the honest answer starts with a correction: a transformer is a neural network, one architecture inside a seventy-year-old family. The real comparison is between siblings. The multilayer perceptron (MLP) wires everything to everything and cannot move information between positions. The convolutional neural network (CNN) slides one small window and assumes the world is local. The recurrent neural network (RNN) carries a notebook from step to step and cannot skip ahead. The transformer lets every position read every other position, with the reading weights computed from the content itself, and that single wiring choice is why your chatbot is not an RNN. This primer walks the family, does the attention arithmetic by hand, counts the parameters, and ends where the inventors themselves now argue about what replaces their creation.

The one sentence to keep Neural network is the family. Transformer is one wiring pattern in it. The engine never changed; the wiring did.

Researched October 2026, from the primary sources in Sources: the papers themselves, the researchers' own essays and interviews, and the labs' official model cards.

Flat illustration of five sibling characters built from the same nodes and connecting lines, each wired differently: a plain mesh, one with a sliding window over its eye, one carrying a backpack on a looping path, and the tallest in the center connected by thin lines to all the others at once.
Same family, different wiring. Every character here is weighted sums and nonlinearities, trained the same way.

The brief

A category, and its loudest member

A transformer is a neural network the way a sedan is a car. Neural network names the category: layers of weighted sums passed through nonlinearities, with the weights fitted by gradient descent. Transformer names one wiring pattern inside that category, published in 2017, which has since taken over language, vision, speech, and protein folding. So the useful question is not transformer or neural network. It is transformer versus its siblings, the MLP, the CNN, and the RNN, and the answer is a single design choice: how information is allowed to move. In an MLP it cannot move between positions at all. In a CNN it moves locally, through a small window. In an RNN it moves one step at a time, carried in a state. In a transformer every position reads every other position directly, and the strength of each read is computed from the content, not fixed by the wiring. Everything else in this primer is a consequence of that choice.

How it works

One engine, four wirings

Every architecture below is the same machine underneath: weighted sums, nonlinearities, gradient descent. What differs is what connects to what. Tap a card to open it.

Strip any architecture in this primer down and you find the same layer, repeated: take the incoming numbers, multiply each by a learned weight, add a learned offset, and bend the result through a fixed nonlinear curve. Stack enough of these and the stack can approximate almost any pattern, provided gradient descent can find the weights. Training is that search: measure the error, use the chain rule to assign each weight its share of the blame (that is backpropagation), and nudge every weight a little downhill. Repeat billions of times.

$$a^{(l)} = g\!\left(W^{(l)} a^{(l-1)} + b^{(l)}\right)$$

Reading it: $a^{(l)}$ is the signal leaving layer $l$, and $a^{(l-1)}$ is the signal that entered it. $W^{(l)}$ is the layer's weight matrix, the learned knobs. $b^{(l)}$ is a bias, one learned offset per output. $g$ is the nonlinearity, a fixed bending curve like the rectified linear unit (ReLU). The superscripts are just layer numbers.

Example: Rosenblatt's 1958 perceptron was exactly one such layer with a hard threshold. It could only learn patterns one straight line can separate, and Minsky and Papert proved in 1969 that it cannot represent XOR. The 1986 Rumelhart, Hinton and Williams paper in Nature showed hidden layers trained by backpropagation learn their own features and clear that wall. The engine has not changed since. Only the wiring has.

The multilayer perceptron is the layer above, stacked, with no sharing and no shortcuts: every input connects to every unit in the next layer. It assumes almost nothing about the data, which is its weakness. It has no idea that two neighboring pixels, or two neighboring words, are related; position is just another coordinate to memorize. The input size is fixed, and the parameter count explodes with it: a single layer from 8 inputs to 16 outputs already carries 144 learned numbers, counted exactly in Fig. 3 below.

Example: show an MLP a sentence as a fixed grid of word slots and it treats word 1 and word 9 as unrelated addresses. Lengthen the sentence and you must rebuild the network. Every later architecture in this primer exists to fix one of these two facts: the explosion, or the blindness to structure.

A convolutional network makes the opposite bet from the MLP: a useful pattern (an edge, a corner, a syllable) is useful everywhere, so learn one small set of weights, a kernel, and slide it across the whole input. LeCun's LeNet-5 (1998) fixed the template: local receptive fields, shared weights, then subsampling to shrink the map. The bias is locality plus translation tolerance, and it pays in parameters: the same detector serves every position instead of being relearned at each one. The cost is reach. Two distant positions only meet after many layers of sliding and shrinking.

Example: AlexNet (2012) scaled this wiring to 60 million parameters and won ImageNet with a top-5 error of 15.3 percent against 26.2 percent for second place, the result that restarted the field. And the obituary keeps failing: ConvNeXt, a pure convnet modernized in 2022, reached 87.8 percent ImageNet top-1 and beat transformer rivals on detection and segmentation benchmarks.

A recurrent network reads one element at a time and carries a single state vector forward, updating it at each step. Any length works, because the same weights are reused at every step. But the past reaches the present only through that one carried state, squeezed at every step, and training signals fade or explode across long spans.

$$h_t = f\!\left(x_t,\ h_{t-1}\right)$$

Reading it: $h_t$ is the carried state after step $t$. $x_t$ is the input at step $t$. $h_{t-1}$ is the state from the step before. $f$ is the learned update that merges the new input into the carried past.

The long short-term memory network (LSTM), from Hochreiter and Schmidhuber in 1997, repaired the fading with a memory cell whose self-loop has weight one, the constant error carousel, guarded by input and output gates; the paper showed it bridging gaps of more than 1,000 steps. One credit correction the textbooks often miss: the famous forget gate is not in the 1997 paper. Gers, Schmidhuber and Cummins added it in 1999 and 2000. Even repaired, the wiring stays sequential: step 400 cannot start until step 399 finishes, and everything the model knows about word 1 must survive 399 squeezes to influence word 400.

Example: before 2017, this was how machines translated. Google Translate ran on LSTMs, and the decoder had to hold an entire sentence's meaning inside one state vector at the end of the sentence. Attention began as a patch for exactly that squeeze.

Bahdanau, Cho and Bengio (2014) bolted a lookup onto an RNN translator: instead of forcing the decoder to work from one squeezed sentence vector, let it look back at every encoder state, weighted by how relevant each one is to what it is about to write. The weights are not wired in advance; they are computed from the content, every time. That is the whole invention. Relevance becomes arithmetic: score each candidate against what you are looking for, turn the scores into shares, and take the weighted blend.

Example: translating "the cat sat" into French, the decoder writing "chat" scores the encoder's states and puts most of its weight on "cat", a little on "the", almost none on "sat". Nobody programmed that alignment. The scoring learned it, because looking at the right word lowered the error.

Vaswani and co-authors asked what happens if the patch becomes the building and the RNN and convolutions are deleted entirely. What remains, stacked six times in the original, is a block with two sub-layers. First, multi-head self-attention: every token looks at every token, in several parallel heads that can each track a different relation. Second, a position-wise feed-forward network, which is exactly an MLP, applied to each token separately. Around each sub-layer sit a residual connection (add the input back) and layer normalization, the plumbing that lets the stack go deep without the signal dying.

$$\mathrm{FFN}(x) = \max\!\left(0,\ xW_1 + b_1\right) W_2 + b_2$$

Reading it: $x$ is one token's vector. $W_1$ widens it from $d_{model}$ to $d_{ff}$, 512 to 2048 in the base model. $\max(0, \cdot)$ is the ReLU nonlinearity. $W_2$ squeezes the vector back to $d_{model}$. $b_1$ and $b_2$ are the biases. This is card 2's MLP, verbatim, living inside every transformer block.

One more ingredient, because of a catch Fig. 1 makes concrete: attention alone cannot tell word order, so the model adds a positional encoding, a position signal stirred into each token before attention runs. The base model from the paper: 6 layers, width 512, feed-forward 2048, 8 heads, 65 million parameters, trained in about 12 hours on 8 P100 GPUs, scoring 27.3 BLEU (the standard translation quality score) on English to German, better than every prior system including ensembles.

Example: count the block's parts and the family resemblance is unavoidable. Attention moves information between tokens; the MLP does the thinking inside each token; the engine training both is card 1's, unchanged since 1986.

Flat illustration of seven round tokens floating in a row, connected to each other by thin curved lines like a web of glances, with three thick rust red lines and one softly glowing token in the middle.
Self-attention: every token can read every other token, and how much it listens is computed, not wired.
One sentence, three wirings Same terms

Same terms, same roles, one sentence. The point is to watch position 7 reach position 14 under three different rules.

PositionOne slot in the data.
ValueThe numbers sitting at a position.
ReceiverThe position being updated.
SenderA position whose value can affect the receiver.
Influence amountHow much a sender affects the receiver.
Learned weightsThe model knobs, fixed after training.
NeighborhoodThe small nearby group around the receiver.
NotebookRecurrence only: one summary value carried forward.

Sentence: Nora put the letter in the drawer, went out, came back, and opened it. The receiver is position 14, it. The sender that matters is position 7, drawer, because a drawer is the thing being opened.

1Nora 2put 3the 4letter 5in 6the 7drawer 8went 9out 10came 11back 12and 13opened 14it

Convolution

Senders the receiver can use
Only senders inside the neighborhood: positions 12, 13, and 14.
Influence amount for drawer
Zero in this layer, because position 7 is outside the neighborhood.
Learned weights
The filter that checks the neighborhood.
Notebook
None.
Result for it: gets the local clue from opened, but drawer needs more layers to arrive.

Recurrence

Senders the receiver can use
Position 14 directly; positions 1 to 13 only through the notebook.
Influence amount for drawer
Not stored separately; only whatever of drawer remains in the notebook.
Learned weights
The update rule that rewrites the notebook.
Notebook
Must carry drawer from position 7 through position 13.
Result for it: works only if the notebook did not fade drawer along the way.

Attention

Senders the receiver can use
All allowed positions, including position 7.
Influence amount for drawer
Computed fresh; can be high because opened plus it matches drawer.
Learned weights
Compare values and mix sender values by influence amount.
Notebook
None in the basic layer.
Result for it: directly pulls in drawer, so the value for it now points to drawer.

The pattern is the whole lesson: convolution is blocked by distance in one layer, recurrence depends on the notebook remembering, and attention can jump straight back to the sender.

Attention, with actual numbers Fig. 1

One query, three tokens, two-number vectors. Small enough to check with a pencil, and it is the real computation, not a metaphor. One tap per step.

$$\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right) V$$

Reading it: $Q$ holds the queries, what each token is looking for. $K$ holds the keys, what each token advertises. $V$ holds the values, what each token hands over when attended to. $d_k$ is the key length, 64 in the base model. The small $T$ means transpose, flipping the matrix so queries can be dotted with keys. Softmax turns each row of scores into shares that sum to 1, and those shares blend the values.

With this primer's numbers plugged in: scores of 1, 0, and 1, divided by root 2, give 0.707, 0, 0.707. Softmax turns them into shares of 0.401, 0.198, 0.401, and the blended output is the vector [0.802, 0.599]. Same formula, bigger vectors, more heads: that is the whole distance from this example to the 2017 paper.

Why it won: the cost of one layer Fig. 2

The 2017 paper's own comparison (its Table 1), made live. Width is fixed at 512 and the convolution kernel at 3, the paper's regime. Drag the sequence length and watch who pays what.

128 tokens
Self-attention

Recurrent

Convolutional

Work counts the multiply-adds in one layer, roughly, and the bars use a log scale so the small end stays visible. Sequential steps are the operations that must finish before later ones can start. Path length is how many steps a signal crosses between the first and last positions.

Count the knobs Fig. 3

Parameters are the learned numbers, and an architecture is mostly a decision about how many you need and where they sit. Set the three numbers that define a transformer and watch the count. The defaults are exactly the 2017 base model.

512
2048
6
Attention, per layer
Feed-forward, per layer
All layers
Hand-checkable, from card 2: one MLP layer, 8 in to 16 out144
Attention alone, width 8, two heads256
One full block, width 8, feed-forward 32768

At width 8 the whole transformer block costs 768 knobs, and 512 of them are the MLP inside it. Attention's own projections are 256. The part that sounds exotic is the minority of its own block.

Weights only: biases, layer norms, and token embeddings are not counted here. The paper's 65 million total for the base model adds the embeddings and the output projection, which at this size are the larger half. Attention counts as 4 times d squared (the query, key, value, and output projections); the feed-forward counts as 2 times d times dff.

Timeline

Seventy years of wiring

The landmarks only: the moments the wiring changed, plus the moments the old wiring answered back. One tap per step, or use the arrow keys.

Key voices

The people who built it, and what they think it is

Each view is from the person's own paper, essay, interview, or code, linked under their card.

Predictions

Where leaders think this goes

Positions as of October 2026, each attributed to its people, venue, and date. Nobody here argues about whether the transformer is a neural network. The argument is about its successor.

Where they agree

  • It is all one family. Vaswani and co-authors (2017) present the transformer as a network architecture among others, and LeCun, Bengio and Hinton's 2015 Nature synthesis treats CNNs and RNNs as members of one backprop-trained family. No source in this primer argues the transformer is not a neural network. The disagreement is only ever about wiring.
  • A successor must be obviously better, not slightly better. Llion Jones (NVIDIA GTC panel, March 2024) states the incumbent's rule, and the shipped record backs him: every frontier model whose architecture is publicly verifiable in October 2026 is still transformer-based.

Split 1: keep it, or hybridize it?

OpenAI (gpt-oss); the DeepSeek team

Keep the transformer and reinvent its insides. DeepSeek-V3 (December 2024) is a transformer whose novelties live inside the parts: latent attention and a mixture-of-experts (MoE) feed-forward, 671B total parameters with 37B active. OpenAI's open gpt-oss models (August 2025) are likewise MoE transformers. The block survives; its contents evolve.

Albert Gu and Tri Dao; AI21; NVIDIA; the Qwen team

Replace most of the layers, keep a few. Mamba (2023) drops attention entirely for a selective state-space core. Jamba (2024) ships about one attention layer per seven Mamba layers. NVIDIA's Nemotron-H (2025) replaces the majority of attention layers and claims up to 3x faster inference. Qwen3-Next (September 2025) runs three linear-attention layers per gated-attention layer.

Split 2: replace the paradigm, four different bets

  • RWKV (Bo Peng and co-authors, EMNLP Findings 2023). Train like a transformer, infer like an RNN: constant state at generation time, no growing cache to feed.
  • xLSTM (Maximilian Beck and co-authors, 2024). The 1997 wiring modernized, exponential gating plus matrix memory, scaled to billions of parameters and reported competitive with transformers and state-space models.
  • Diffusion language models (Songlin Nie and co-authors, LLaDA, 2025; Inception's Mercury; Google DeepMind's Gemini Diffusion). Generate by denoising the whole answer at once instead of one token at a time. The honest footnote: LLaDA is still parameterized by a transformer. This bet challenges autoregression, not attention.
  • JEPA and world models (Yann LeCun, 2022 onward). Stop predicting tokens entirely. Predict representations of the world and plan inside them; he left Meta in 2025 to pursue it at his own startup.

Split 3: what can next-token prediction actually learn?

Ilya Sutskever

From his 2023 Dwarkesh interview: predict the next token well enough and the model is forced to learn the process that generated the tokens. The training signal looks thin and is not; it is a compression of the world, and it can go much further than it appears.

Yann LeCun

From his June 2022 position paper: autoregressive prediction compounds its own errors over long generations, and no world model gets built along the way. As a road to intelligence, token prediction is the wrong objective, however far it scales.

The honest asterisk

For the closed frontier (GPT-5, Claude, Gemini), no primary source in this research discloses the architecture. Calling those models transformers is inference from lineage and from the absence of any announced replacement. This primer labels it as inference, not fact, and the camps above rest only on what labs have published.

Takeaways

Takeaways

The difference between a transformer and a neural network is the difference between a category and its most famous member. Compare the members instead, and the whole story is one wiring decision: who is allowed to talk to whom, and at what cost. The engine underneath, gradient descent on weighted sums and nonlinearities, has not changed since 1986. Even the transformer's own inventors now split over what wiring comes next.

  • Category first. Transformer is an architecture; neural network is the family it belongs to. Any sentence that pits the two against each other has made the mistake this primer exists to fix.
  • The difference is movement. In an MLP, information cannot move between positions. In a CNN it moves locally, through a shared window. In an RNN it moves one carried step at a time. In a transformer, every position reads every other position, weighted by content.
  • Half the transformer is an MLP. Every block pairs attention with a feed-forward network, and at toy sizes most of the block's parameters are the MLP's. Karpathy's split is the one to keep: attention is communication, the MLP is computation.
  • Attention's price is the square. Reading everything costs work that grows with the square of the sequence length, while the signal path shrinks to a single step. Both halves of that trade drive today's research: hybrids keep attention only where it pays.
  • Bias is a bargain, not a flaw. CNNs and RNNs assume structure and win when data is scarce, as ConvNeXt's 2022 comeback and the Vision Transformer's data hunger show from opposite sides. The transformer assumes almost nothing and wins at scale.
  • The 2026 frontier is a blend. Mixture-of-experts feed-forwards are near-universal, attention survives in a minority of layers in the hybrid lines, and no pure challenger holds the frontier yet.

Keep exploring

Keep exploring

Sources

Sources

Primary sources: the papers themselves, the labs' official model cards and docs, and the researchers' own essays, interviews, and code.