By Sagi Shaier · 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 training signal can fade or blow up. Gradients pass through many repeated steps, so they can become very small or very large.
- Old information can be overwritten. The same hidden state is reused again and again, so early details get crowded out by later updates.
- Long-range links are indirect. A token near the start can affect a token near the end only through many states in between.
- 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.

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.

Two details make this work for text generation:
- Positional encoding. Without a chain the model has no built-in sense of order, so a vector that marks each position is added to each token's embedding before the first layer.
- The causal mask. A model that writes text one token at a time must not see the tokens after the one it is predicting. In a decoder-only transformer, the kind GPT-style models use, a mask lets each position attend only to itself and the positions before it.
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:

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.

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.

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

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

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])
23280The 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:
- Leaving out the causal mask in a decoder. Each position can then see the future tokens it is trained to predict.
- Thinking the FFN mixes tokens. It runs on each position separately, and attention does the mixing between positions.
- Returning a different width from a sublayer. The residual addition needs the sublayer output to have $d_{model}$ features, the same as its input.
- Normalizing over the wrong axis.
nn.LayerNorm(d_model)normalizes the features of each token, which is the last axis of a(B, T, d_model)tensor.
Related concepts
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.