Four networks, four assumptions about the data
If you already know what a neuron, a loss function and gradient descent are, a practical question remains: what changes from one architecture to the next, and why does each piece suit images, sequences or text? I explain that step by step in How neural networks work, so I won’t repeat it here.
Here’s what matters: they are all still functions with parameters that get adjusted bit by bit. What changes is the assumption you build into the structure. An architecture is a bet on how your data is organised, and if the bet is a good one, you need fewer parameters and fewer examples to learn.
- Dense: assumes nothing.
- Convolutional: locality and translation invariance.
- Recurrent: a state that travels along the sequence.
- Transformer: global attention, where every position can look at any other.
Each section comes with an example that checks itself with assert: if you run it and no error is raised, it does what the text says.
Dense network: the baseline with no assumptions
A dense (or fully connected) layer makes every output depend on all the inputs. In PyTorch, nn.Linear applies an affine transformation, y = xAᵀ + b, and its weights have shape (out_features, in_features). According to the PyTorch documentation, an nn.Linear(20, 30) layer applied to a batch of 128 vectors of 20 values returns an output of size [128, 30].
import torch
from torch import nn
torch.manual_seed(0)
capa = nn.Linear(20, 30)
x = torch.randn(128, 20)
y = capa(x)
assert y.shape == (128, 30)
assert capa.weight.shape == (30, 20) # (outputs, inputs)
# The same by hand: y = x A^T + b
assert torch.allclose(y, x @ capa.weight.T + capa.bias, atol=1e-5)
print("Dense layer: shapes and formula checked")
The last check is the key one: there is nothing more to it than a matrix multiplication and an addition.
It is the starting point because it presupposes no structure at all. That is a virtue with tabular data or feature vectors, where the order of the columns means nothing, and a problem with images: the book Dive into Deep Learning points out that treating an image with fully connected layers could require billions of parameters (D2L, section 7.1). As a rule of thumb (not a measured figure): if your data has no spatial or temporal structure, a dense network is the first reasonable candidate.
Convolutional network: locality and shared weights
For the first layers facing an image, D2L starts from two principles:
- Translation invariance: the network should respond in the same way to a given patch, wherever it appears.
- Locality: the first layers focus on local regions, without considering distant areas. Those local representations are then aggregated, and the deeper layers pick up longer-range features.
A convolutional layer is equivalent to a fully connected layer restricted by those two principles. The learnable weights are the kernel (or filter), the same at every position. According to D2L, this brings the count down from billions of potential parameters to a few hundred, without changing the dimensions of the input or of the hidden representation.
To see it without libraries, here is a convolution written by hand with NumPy (strictly speaking, a cross-correlation, which is what the convolutional layers in libraries actually compute). The filter detects a vertical edge; we shift the edge two columns and check that the response shifts by the same amount. It uses no random numbers.
import numpy as np
def convolucion(imagen, nucleo):
k = nucleo.shape[0]
alto, ancho = imagen.shape[0] - k + 1, imagen.shape[1] - k + 1
salida = np.zeros((alto, ancho))
for i in range(alto):
for j in range(ancho):
salida[i, j] = np.sum(imagen[i:i + k, j:j + k] * nucleo)
return salida
nucleo = np.array([[-1.0, 1.0], [-1.0, 1.0]]) # 4 weights: dark -> light edge
img = np.zeros((8, 8)); img[:, 4:] = 1.0 # edge between columns 3 and 4
img_desplazada = np.zeros((8, 8)); img_desplazada[:, 6:] = 1.0 # two columns to the right
r1 = convolucion(img, nucleo)
r2 = convolucion(img_desplazada, nucleo)
assert np.argmax(r1[0]) == 3 and np.argmax(r2[0]) == 5 # the response shifts
assert np.array_equal(r1[:, :5], r2[:, 2:]) # and has the same shape
assert nucleo.size == 4 # the filter has 4 weights
print("Convolution: translation invariance checked")
The filter has 4 weights. A dense layer connecting the same 8×8 image (64 inputs) to a 7×7 output (49 values) would have 64 × 49 = 3,136 weights, not counting biases. That is the saving in scale that D2L describes.
The price is the flip side of the advantage: the features are translation invariant, and each activation only incorporates local information. If the absolute position matters in your problem, that assumption works against you. For the historical background to why these networks took off, there is the article on the takeoff of deep learning.
Recurrent network and LSTM: a state that runs along the sequence
With a sequence (a sentence, a time series) the order matters and the length varies. A recurrent network keeps a hidden state ht−1 that summarises what has been seen up to step t−1, and updates it with ht = f(xt, ht−1). According to D2L, this is how P(xt | xt−1, …, x1) is approximated by P(xt | ht−1).
Piece by piece: at each step the current input and the previous state are concatenated and passed through a fully connected layer with an activation function. The parameters (Wxh, Whh and the bias bh) are the same at every step. That is why the order is built into the structure, and why a longer sequence adds no parameters.
A plain recurrent network has a short memory in practice. The LSTM (long short-term memory) adds input, forget and output gates: three fully connected layers with a sigmoid, with values in (0, 1), which control when the state is updated and when it is reset. These mechanisms are learned too (D2L, section 10.1). The equations, according to the PyTorch documentation, are ct = ft ⊙ ct−1 + it ⊙ gt and ht = ot ⊙ tanh(ct); that is why h always lies in (−1, 1).
import torch
from torch import nn
torch.manual_seed(0)
rnn = nn.LSTM(10, 20, 2) # 10 inputs, hidden state of 20, 2 layers
entrada = torch.randn(5, 3, 10) # (steps, batch, features)
h0 = torch.randn(2, 3, 20)
c0 = torch.randn(2, 3, 20)
salida, (hn, cn) = rnn(entrada, (h0, c0))
assert salida.shape == (5, 3, 20)
assert hn.shape == (2, 3, 20) and cn.shape == (2, 3, 20)
assert salida.abs().max() <= 1.0 # h = o * tanh(c) lies in (-1, 1)
# The last step of the last layer matches the final state h_n
assert torch.allclose(salida[-1], hn[-1], atol=1e-6)
print("LSTM: shapes and range checked")
Notice that the five steps are computed one after another: each step needs the state from the one before. That sequential dependency makes the computation hard to parallelise, and it is one of the reasons the authors of the Transformer give for proposing something different.
Transformer: attention instead of recurrence
In June 2017, Vaswani and colleagues proposed, in “Attention Is All You Need”, an architecture based solely on attention mechanisms, with no recurrence or convolutions. Their starting point was that the dominant sequence transduction models were recurrent or convolutional networks in an encoder-decoder configuration. Attention establishes global dependencies between positions and, according to the authors, allows considerably more parallelisation (NeurIPS 2017 version).
One piece you can look at: the encoder is a stack of 6 identical layers, each with two sub-layers, multi-head attention over itself (self-attention) and a fully connected network applied position by position. In self-attention, each position works out how much weight to give to all the others; there is no state travelling step by step.
The nn.MultiheadAttention layer implements the original architecture, and its documentation presents it as a reference implementation for basic understanding, with limited functionality compared with newer architectures: it is for learning, not a production model. embed_dim is split across num_heads (each head works with embed_dim // num_heads). With batch_first=True, the input has shape (N, L, E): batch, sequence length and dimension. In attn_mask, a True means that position cannot be attended to.
import torch
from torch import nn
torch.manual_seed(0)
N, L, E = 2, 5, 16
atencion = nn.MultiheadAttention(E, num_heads=4, batch_first=True)
x = torch.randn(N, L, E)
salida, pesos = atencion(x, x, x) # query = key = value
assert salida.shape == (N, L, E)
# Each row of weights shares out the attention: it sums to 1
assert torch.allclose(pesos.sum(dim=-1), torch.ones(N, L), atol=1e-5)
# Mask: no one can attend to the last position
mascara = torch.zeros(L, L, dtype=torch.bool)
mascara[:, -1] = True
_, pesos_m = atencion(x, x, x, attn_mask=mascara)
assert torch.all(pesos_m[:, :, -1] == 0)
print("Attention: shapes, rows summing to 1 and mask checked")
With the mask, the last position receives weight 0 in every row and the rest is shared out among the others, which still sum to 1.
As for results, this is what the authors claim in the arXiv version of the paper, without independent verification in the sources consulted: 28.4 BLEU on the WMT 2014 English-to-German translation task, more than 2 BLEU above the best previous results, and 41.8 BLEU on English-to-French with a single model after 3.5 days of training on eight GPUs. BLEU is a score that compares machine translation with human reference translations; it is useful for comparing systems under the same conditions, not a definitive verdict on quality.
A map for choosing, and mistakes in approach
| Network | Built-in assumption | Where it fits | Price of the assumption |
|---|---|---|---|
| Dense | None | Feature vectors with no spatial or temporal structure | With images, billions of potential parameters |
| Convolutional | Locality and translation invariance | Images | Each activation only sees local information |
| Recurrent / LSTM | A state summarises the past | Sequences | Step-by-step computation, hard to parallelise |
| Transformer | Any position can attend to any other | Sequences and text | The sources consulted do not detail its memory or compute cost |
The sources consulted also make no empirical comparison between architectures, so I don’t state figures on which one performs best on each task.
Where it breaks
- A dense network on large images: the number of parameters explodes and you ignore the structure you already have.
- Expecting a convolutional network to be sensitive to position: if where something appears matters, translation invariance won’t help you on its own.
- Forgetting that an LSTM goes step by step: long sequences mean long sequential computation.
- Mistaking the reference layer for a complete model:
nn.MultiheadAttentionis a piece for understanding, not a trained Transformer.
An opinion, marked as such: before choosing an architecture, look at your data. In most real problems it matters more than the architecture, and a model that gets the training set right and fails on the test set has memorised, whatever its type. If that happens to you, this article on overfitting tells you how to detect it.
Practice
Take the four examples and change one size at a time: the convolution kernel to 3×3, the LSTM’s hidden_size, or the attention’s num_heads (it must divide E). Before running, write in an assert how you think the output shape will change, and check whether you were right.
Optional exercise: count the parameters of an nn.Linear and of a convolution on the same input, and compare the scale, as we did with 4 versus 3,136.
For further reading, Kia’s article on the takeoff of deep learning in the 2010s gives the context for why deep networks became practical; it does not cover transformers, so for those the original paper linked above is the best place to start. And if you need to revise neurons, loss and gradient descent, go back to How neural networks work.
Sources
- Attention Is All You Need (arXiv:1706.03762)
- Attention is All you Need (NeurIPS 2017, PDF)
- 7.1. From Fully Connected Layers to Convolutions — Dive into Deep Learning 1.0.3
- 9.4. Recurrent Neural Networks — Dive into Deep Learning 1.0.3
- 10.1. Long Short-Term Memory (LSTM) — Dive into Deep Learning 1.0.3
- LSTM — PyTorch documentation
- MultiheadAttention — PyTorch documentation
- Linear — PyTorch documentation 2.15
Translated and adapted by Ollie.