QuiddityML

By · 9 November 2026 · 8 min read

How transformers work, explained for someone who has never seen one

Why transformers dropped the recurrent chain of RNNs, what happens inside one transformer layer (self-attention, the feed-forward network, residual connections and LayerNorm), how layers stack into a GPT-style model, and a runnable PyTorch layer.

A transformer is a neural network for sequences in which every position reads the other positions directly through attention, with no step-by-step chain from one position to the next. It is built from one kind of layer repeated many times, and GPT-style language models are stacks of these layers. Models read tokens, which can be whole words or pieces of words, and the examples here use short words as tokens to keep them small.

The problem with the recurrent chain

Before transformers, sequence models were mostly recurrent neural networks (RNNs). An RNN reads one token at a time and carries a hidden state, a vector of numbers it updates at each step from the current token and the previous state:

$$h_1 \rightarrow h_2 \rightarrow h_3 \rightarrow h_4 \rightarrow \ldots$$

That chain causes four connected problems.

The tokens the, cute and axolotl feed the chain h1, h2, h3. Four problems are listed: the training signal can fade or blow up, old information can be overwritten, long-range links are indirect, and training is hard to parallelize because step 10 waits for step 9.

  1. The training signal can fade or blow up. Gradients pass through many repeated steps, so they can become very small or very large.
  2. Old information can be overwritten. The same hidden state is reused again and again, so early details get crowded out by later updates.
  3. Long-range links are indirect. A token near the start can affect a token near the end only through many states in between.
  4. Training is hard to parallelize across positions. Step 10 needs step 9 first, so the model cannot compute all positions at once, which makes training on very large amounts of text slow.

LSTMs added gates that control what the state keeps, forgets and writes, which helped with forgetting and with gradient flow. They kept the chain. Attention, explained in what is attention in deep learning, let the decoder of an RNN encoder-decoder look back over all the encoder's states instead of only the last one. That fixed the single-vector bottleneck, and the encoder and decoder were still RNNs.

The 2017 idea: attention as the main operation

In 2017 the paper "Attention Is All You Need" made a stronger move. Instead of adding attention on top of an RNN, it removed the recurrent chain and let positions communicate through attention directly.

Top: attention as an add-on, where recurrence still processes h1 to h4 one step at a time and attention is added to the RNN. Bottom: attention as the main operation, where the, cute and axolotl connect to each other directly with no recurrent chain, which lets training run across positions in parallel.

The operation is called self-attention. Each position compares itself with the positions it is allowed to see, turns those comparisons into weights with softmax, and builds its new representation as a weighted sum. That is the same score, softmax and weighted-sum recipe as attention in an RNN, now running between the positions of one sequence. Since no position waits for the one before it, all positions are computed at the same time.

Top: RNN encoder-decoder attention, where the decoder state is scored against h1 to h4, softmax gives the weights and the weighted sum gives a context that is combined to produce the output. Bottom: transformer-style self-attention, where every position x1 to x5 scores every position at once. Both compute scores, softmax weights and a weighted sum.

Two details make this work for text generation:

What happens inside one transformer layer

One layer has two sublayers: masked self-attention, then a feed-forward network. Each sublayer gets its input through a normalization step called LayerNorm, and its output is added back to the layer's input through a residual connection. The sections below take these one at a time.

Masked multi-head self-attention

The attention sublayer runs several attention computations side by side, called heads. Each head has its own learned projections, so each can learn a different weighting pattern over the same positions. Each head returns a few features per token, and the heads' outputs are placed side by side and mixed by one more learned matrix. The result has the same number of features per token as the input. The details of how a head computes its weights are a topic of their own.

The feed-forward network

Attention routes information between positions, and its last step is a weighted sum, which is a linear blend of vectors. To let the model compute more than linear blends, each layer adds a feed-forward network (FFN) after attention. The FFN is a small two-layer neural network.

The FFN does not mix tokens with each other. It runs the same network, with the same weights, on each position separately:

The same FFN with shared weights runs on x_0, x_1 and x_2 separately, giving y_0 = FFN(x_0), y_1 = FFN(x_1) and y_2 = FFN(x_2). Attention already mixed information across tokens, and the FFN transforms each position on its own.

Each token vector has $d_{model}$ features. The FFN expands it to a larger size $d_{ff}$, applies a nonlinear activation $\sigma$, then projects it back to $d_{model}$:

$$\text{FFN}(x) = \sigma(xW_1 + b_1)\,W_2 + b_2$$

Here $W_1$ has shape $d_{model} \times d_{ff}$ and $W_2$ has shape $d_{ff} \times d_{model}$. The bias vectors are $b_1$ and $b_2$. The original transformer used ReLU for $\sigma$, and many GPT-style models use GELU. A common setting is $d_{ff} = 4 \times d_{model}$, so a model with 768 features per token uses a hidden size of 3,072.

A token vector of size d_model goes through linear 1 to the expanded size d_ff, an element-wise ReLU or GELU, and linear 2 back to d_model. For a whole batch the shape goes from (B, T, d_model) to (B, T, d_ff) and back to (B, T, d_model). The common setting is d_ff = 4 × d_model.

For a batch of $B$ sequences with $T$ tokens each, the shape goes from $(B, T, d_{model})$ to $(B, T, d_{ff})$ and back to $(B, T, d_{model})$. The batch and position axes are untouched.

Residual connections

A residual connection, also called a skip connection, adds a sublayer's output to its input instead of replacing the input. A plain block computes $y = F(x)$. A residual block computes:

$$y = x + F(x)$$

so the sublayer $F$ only has to learn the change. Taking the derivative gives $\partial y/\partial x = 1 + \partial F/\partial x$. The 1 comes from the identity path, and it gives gradients a direct route back to earlier layers whatever the sublayer does. If the best thing a sublayer can do is leave its input alone, it can learn to make $F(x)$ small. For the addition to work, every sublayer has to return the same shape it received.

A plain block computes y = F(x) and must learn the whole next representation. A residual block computes y = x + F(x) and learns only the change, with an identity path that gives gradients a shorter route backward.

LayerNorm

After embeddings, attention updates and residual additions, the features of a token vector can drift to very different scales. A very large feature can then dominate the dot products in the next sublayer. LayerNorm gives each token vector a controlled scale. For one token vector $x$ with $d_{model}$ features, it computes the mean $\mu$ and the variance $\sigma^2$ of those features, then rescales each feature:

$$\hat{x}_i = \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}}$$

The small constant $\epsilon$ avoids dividing by zero. For example, take the 6-feature vector $x = [1, 0, 2, -1, 1, -1]$. Its mean is $\mu = 2/6 \approx 0.33$, its variance is about $1.22$ and its standard deviation about $1.11$. Each feature minus the mean, divided by $1.11$, gives:

$$\hat{x} \approx [0.60, -0.30, 1.51, -1.21, 0.60, -1.21]$$

Left: one token vector before LayerNorm, with one very tall red feature, one near zero and four of middling height. Right: the same vector after LayerNorm, with the features on one controlled scale, centered on zero.

LayerNorm then multiplies by a learned scale $\gamma$ and adds a learned shift $\beta$, one value per feature, so the model can move away from mean 0 and standard deviation 1 where that helps. It normalizes within each token vector and never averages across tokens or across the examples in a batch. That is why transformers use it instead of BatchNorm, which averages over the batch and behaves badly when sequences in a batch have different lengths.

The whole layer

The common GPT-style layer, called pre-norm, applies LayerNorm before each sublayer and then adds the sublayer's output back. With $X$ as the layer's input:

$$X_1 = X + \text{MaskedSelfAttention}(\text{LN}_1(X))$$

$$X_{next} = X_1 + \text{FFN}(\text{LN}_2(X_1))$$

The input X goes through LN_1 and causal self-attention, and the result is added back to X to give X_1. X_1 goes through LN_2 and the FFN, and the result is added back to give X_next. The shape in and the shape out are both B × T × d_model.

The input and output both have shape $(B, T, d_{model})$. The values change and the shape stays the same. The original 2017 transformer used post-norm, $\text{LayerNorm}(x + \text{Sublayer}(x))$, which puts the normalization on the main path. Pre-norm leaves the main path untouched, which is why it trains more easily in very deep stacks.

Stacking layers into a model

A GPT-style model repeats this layer many times. Each layer has its own attention projections, its own output projection, its own FFN weights and its own LayerNorm parameters. The stream keeps its shape from layer to layer, and each layer refines the representations it receives.

Y(0) enters layer 1, which outputs Y(1), then layer 2 outputs Y(2), and so on up to Y(N). Each layer has its own attention projections, output projection, FFN weights and LayerNorm parameters, and the shape stays (B, T, d_model) through every layer.

A transformer layer in PyTorch

LayerNorm first, since its numbers can be checked against the worked example. PyTorch starts $\gamma$ at 1 and $\beta$ at 0, so a fresh layer gives the plain normalized values:

1import torch
2import torch.nn as nn
3 
4x_the = torch.tensor([1., 0., 2., -1., 1., -1.])
5ln = nn.LayerNorm(6)            # starts with gamma = 1 and beta = 0
6print(ln(x_the).detach().round(decimals=2))
1tensor([ 0.6000, -0.3000,  1.5100, -1.2100,  0.6000, -1.2100])

Then a full pre-norm decoder layer. It uses PyTorch's built-in multi-head attention, and the causal mask is a $T \times T$ grid that blocks every position from looking ahead:

1import torch
2import torch.nn as nn
3import torch.nn.functional as F
4 
5 
6class FeedForward(nn.Module):
7    def __init__(self, d_model, d_ff):
8        super().__init__()
9        self.fc1 = nn.Linear(d_model, d_ff)
10        self.fc2 = nn.Linear(d_ff, d_model)
11 
12    def forward(self, x):
13        return self.fc2(F.gelu(self.fc1(x)))
14 
15 
16class TransformerLayer(nn.Module):
17    def __init__(self, d_model, num_heads, d_ff):
18        super().__init__()
19        self.ln1 = nn.LayerNorm(d_model)
20        self.attn = nn.MultiheadAttention(d_model, num_heads, batch_first=True)
21        self.ln2 = nn.LayerNorm(d_model)
22        self.ffn = FeedForward(d_model, d_ff)
23 
24    def forward(self, x):
25        T = x.size(1)
26        # True above the diagonal: position t may not look at positions after t
27        causal_mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1)
28        z = self.ln1(x)
29        attn_out, _ = self.attn(z, z, z, attn_mask=causal_mask)
30        x = x + attn_out
31        x = x + self.ffn(self.ln2(x))
32        return x
33 
34 
35torch.manual_seed(0)
36layer = TransformerLayer(d_model=16, num_heads=2, d_ff=64)
37x = torch.randn(2, 5, 16)          # 2 sequences, 5 tokens each, 16 features per token
38print(layer(x).shape)
39print(sum(p.numel() for p in layer.parameters()))
1torch.Size([2, 5, 16])
23280

The output has the same shape as the input, which is what lets layers stack. Attention accounts for 1,088 of the 3,280 parameters and the two LayerNorms for 64. The FFN holds the other 2,128, about two thirds of the layer's weights. self.attn(z, z, z, ...) passes the same normalized stream three times because in self-attention the positions attend to each other. If a model trained with this layer looks far too good on its training text, check the causal mask first, since a missing mask lets each position read the token it is supposed to predict.

When transformers fit, and common mistakes

Transformers fit sequence tasks where the training data is large, because their positions are computed in parallel and training scales to very large amounts of text. GPT-style language models stack the decoder-only layer shown here.

Mistakes that come up often:

What is attention in deep learning explains the score, softmax and weighted-sum recipe that self-attention reuses. Recurrent neural networks and LSTMs show the chain that transformers removed. What is a language model covers the next-token objective that GPT-style transformers are trained on.

QuiddityML teaches the transformer layer in the Intro to NLP track, with the feed-forward network and the layer as their own concepts. The exercises include writing LayerNorm by hand, spotting bugs in a TransformerLayer, and typing the full pre-norm decoder layer from scratch.