Search

Search papers and lessons

Encoder-Decoder Architecture

Level 3 · 11 min read

An encoder-decoder network squeezes its input into a compact middle representation and then grows an output from it, which is the shape behind translation, summarising, autoencoders and image segmentation.

On this page

  • Colour = topic mix
  • Linear algebra
  • Neural network basics
  • Architectures
  • Discrete math
  • Sign in to see your progress

TL;DR

An encoder-decoder network has two halves joined at a middle point. The encoder reads the input and compresses it into a compact internal representation, often called the code or context. The decoder starts from that representation and produces the output one piece at a time. The split means the input and output can have different shapes and lengths, for example a French sentence in and an English sentence out.

The bottleneck in the middle is both the point and the cost. Because everything the decoder knows must fit through it, the network learns to keep the parts of the input that matter for the output and drop the rest.

Where you'll see it: in machine translation systems, in summarisation models, in autoencoders that learn compressed codes of images, and in U-Net style networks that label every pixel of a medical scan.

Intuition

A reader and a writer with a note in between

Picture a translator who has to pass a message between two rooms without speaking. The first person reads the whole source paragraph, then writes a short note on a card. The card is the only thing that crosses the door. The second person, who has never seen the original, reads the card and writes out a paragraph in the other language.

That is an encoder-decoder. The first person is the encoder, the card is the latent representation, and the second person is the decoder. The card has a fixed size, so the encoder has to decide what to keep. If the paragraph is long and the card is small, details get lost. If the card is large, the decoder has more to work with but the system is harder to train and less useful as a summary.

Why split the job at all? Because the input and the output often live in different spaces. A French sentence is a list of French words of one length. An English sentence is a list of English words of a different length, and the two lists have no direct position-by-position match. A single network that maps one list straight to the other has to learn that alignment inside its wiring. Splitting the work into "understand the input" and "generate the output" lets each half specialise, and gives the middle a meaning of its own: a representation of the input's content that does not depend on its surface language.

The same picture works for images. An encoder that shrinks a photo into a short vector of numbers is doing the same job as the first person: keeping the content and discarding the pixel-level noise. A decoder that turns that short vector back into a picture is the second person. If the two halves are trained together to reproduce the original, the middle becomes a compact code for the photo.

flowchart LR
  X[Input sequence or image] --> E[Encoder]
  E --> Z[Bottleneck: code or context vector]
  Z --> D[Decoder]
  D --> Y[Output sequence or image]

The math

Setting up the two functions

Write the input as xx and the output as yy. The encoder is a function fθf_\theta with learnable weights θ\theta. It maps the input to a representation h\mathbf{h}:

h=fθ(x).\mathbf{h} = f_\theta(x).

Here h\mathbf{h} is a vector of fixed length, say dd real numbers. The decoder gϕg_\phi with its own weights ϕ\phi maps that vector to a distribution over outputs:

pϕ(y∣h)=gϕ(h).p_\phi(y \mid \mathbf{h}) = g_\phi(\mathbf{h}).

The vertical bar is read "given". The whole model is the composition of the two, and training adjusts θ\theta and ϕ\phi together so that the output matches the target.

Sequence version

Most encoder-decoder models handle sequences. Let the input be x1,…,xTx_1, \dots, x_T and the output y1,…,ySy_1, \dots, y_S, where TT and SS are lengths that can differ. A recurrent encoder, such as a recurrent neural network or a LSTM, reads the input one step at a time and updates a hidden state (a vector that summarises everything read so far). The final state becomes the context:

st=RNNenc(st−1,xt),c=sT.\mathbf{s}_t = \mathrm{RNN}_\text{enc}(\mathbf{s}_{t-1}, x_t), \qquad \mathbf{c} = \mathbf{s}_T.

The decoder is a second recurrent network that starts from c\mathbf{c} and emits one output symbol per step. At each step it reads the symbol it produced last and its own state, and predicts the next symbol with a Softmax over the vocabulary:

zt=RNNdec(zt−1,yt−1,c),p(yt∣y<t,x)=softmax(Wzt+b).\mathbf{z}_t = \mathrm{RNN}_\text{dec}(\mathbf{z}_{t-1}, y_{t-1}, \mathbf{c}), \qquad p(y_t \mid y_{\lt t}, x) = \mathrm{softmax}(W \mathbf{z}_t + \mathbf{b}).

The notation y<ty_{\lt t} means all the outputs before position tt. The full probability of an output sequence is the product of the per-step probabilities, which becomes a sum after taking logs:

log⁡p(y∣x)=∑t=1Slog⁡p(yt∣y<t,x).\log p(y \mid x) = \sum_{t=1}^{S} \log p(y_t \mid y_{\lt t}, x).

Training maximises this sum over a dataset of input-output pairs. Equivalently it minimises the negative sum, which is the cross-entropy loss of the predicted distributions against the true next symbols. Gradients flow back through the decoder, into the context vector, and through the encoder, so the whole model is trained by Backpropagation with a Gradient Descent optimiser.

Image version

For images the encoder is usually a stack of convolutional layers that shrink the spatial size while increasing the number of channels. The decoder mirrors it with layers that grow the spatial size again, typically transposed convolutions. The output has the same spatial size as the input, but each pixel now carries a label or a value, and the loss is computed per pixel. The reconstruction loss for an autoencoder is the squared error between the output and the input:

L(x)=∥x−gϕ(fθ(x))∥2.\mathcal{L}(x) = \lVert x - g_\phi(f_\theta(x)) \rVert^2.

If the bottleneck has fewer numbers than the input, minimising this loss forces the code to capture the structure that predicts the input best.

A tiny bottleneck by hand

Take a 4-number input and a 2-number bottleneck, with linear maps so the arithmetic is easy to follow. The encoder adds neighbouring pairs:

Wenc=(11000011),Wdec=(10100101).W_\text{enc} = \begin{pmatrix} 1 & 1 & 0 & 0 \\ 0 & 0 & 1 & 1 \end{pmatrix}, \qquad W_\text{dec} = \begin{pmatrix} 1 & 0 \\ 1 & 0 \\ 0 & 1 \\ 0 & 1 \end{pmatrix}.

The decoder copies each bottleneck number to the two positions it came from. Input x=(2,1,0,3)x = (2, 1, 0, 3) goes through these steps:

  1. Encode: h=Wenc x=(2+1,  0+3)=(3,3)\mathbf{h} = W_\text{enc}\,x = (2+1,\; 0+3) = (3, 3).
  2. Decode: x^=Wdec h=(3,3,3,3)\hat{x} = W_\text{dec}\,\mathbf{h} = (3, 3, 3, 3).
  3. Error: ∥x−x^∥2=(2−3)2+(1−3)2+(0−3)2+(3−3)2=1+4+9+0=14\lVert x - \hat{x} \rVert^2 = (2-3)^2 + (1-3)^2 + (0-3)^2 + (3-3)^2 = 1 + 4 + 9 + 0 = 14.

The reconstruction is wrong, and the reason is the bottleneck. The 2-number code only remembers the pair sums, so (2,1)(2, 1) and (0,3)(0, 3) can no longer be told apart from (1,2)(1, 2) and (3,0)(3, 0). A learned encoder would pick the 2 numbers that best separate the likely inputs, and the error would fall. The example shows the trade-off that every encoder-decoder faces: the smaller the code, the more has to be thrown away.

Worked examples

Example
Scoring a translation

A trained model is asked to translate a source sentence into the French target "le chat". Assume the decoder assigns these probabilities, one per output step:

  1. p("le"∣x)=0.7p(\text{"le"} \mid x) = 0.7
  2. p("chat"∣x,"le")=0.5p(\text{"chat"} \mid x, \text{"le"}) = 0.5
  3. p(end∣x,"le","chat")=0.9p(\text{end} \mid x, \text{"le"}, \text{"chat"}) = 0.9

The probability of the whole output is the product:

p("le chat"∣x)=0.7×0.5×0.9=0.315.p(\text{"le chat"} \mid x) = 0.7 \times 0.5 \times 0.9 = 0.315.

The training loss for this example is the negative log of that probability, in nats:

−ln⁡(0.315)≈1.155.-\ln(0.315) \approx 1.155.

Perplexity turns the per-symbol average back into an intuitive number. With three output steps (including the end marker), the per-step loss is 1.155/3≈0.3851.155 / 3 \approx 0.385, and e0.385≈1.47e^{0.385} \approx 1.47. The model is, on average, choosing between about 1.5 equally likely options at each step. A perfect model would score 1.0.

Example
Reading the bottleneck in a realistic autoencoder

A grayscale photo of size 28 by 28 has 784 pixel values. Suppose the encoder compresses it to a code of 32 numbers. The compression ratio is 784/32=24.5784 / 32 = 24.5. The decoder must produce 784 values from only 32.

Now compare two codes. A 32-number code trained on handwritten digits usually reconstructs a clear digit, because 32 numbers are enough to describe which digit it is, its slant and its stroke width. A 2-number code can still separate digits roughly, but blurs the stroke detail. A 784-number code, the same size as the input, can copy the image exactly, which means it has learned nothing about structure. This is why the size of the bottleneck is the main design choice: too small and the output is blurred, too large and the network just memorises pixels.

The same idea applies to text. A translation model with a 512-number context has to fit a whole sentence into 512 numbers. Short sentences fit easily. Very long documents do not, which is one reason the attention idea was introduced: to let the decoder look back at the input directly rather than rely on one vector.

Tradeoffs and failure modes

Encoder-decoders are the right tool when input and output differ in shape, length or meaning, or when there is something to generate. They are the wrong tool when there is nothing to decode, such as one label per input, where an encoder with a classifier head is simpler. Even for pixel labelling, where input and output share a size, a plain bottleneck loses detail, as the table shows.

SituationWhat goes wrongBetter choice
Long input, one fixed-size context vectorEarly details are forgotten by the time the decoder runsAdd [[attention-mechanism
Output the same length as the input (e.g. labelling each pixel)The bottleneck throws away spatial detail the output needsAdd skip connections from encoder to decoder, as in U-Net
Need a smooth, structured code (generation, interpolation)A plain autoencoder code has gaps; random codes decode to noiseA Variational Autoencoder with a probabilistic code
Single tag per input (e.g. sentiment)Nothing to decode; the extra decoder is wastedUse the encoder alone with a classifier head
Training data is smallA large encoder and decoder overfit the examplesSmaller bottleneck, weight decay, or a pretrained encoder

Two failure modes come up repeatedly in practice. The first is exposure bias: during training the decoder is fed the true previous symbol, but at test time it is fed its own guess, which may be wrong, and errors compound. The usual fix is scheduled sampling, which mixes true and predicted symbols during training. The second is posterior collapse in variational models, where the decoder becomes so strong that it ignores the code and the encoder learns nothing useful. Annealing the weight on the regularisation term helps.

History

Autoencoders, the simplest encoder-decoder, were studied for decades as a way to reduce dimension. Hinton and Salakhutdinov showed in 2006 that deep networks trained this way could compress data better than principal components analysis, which put the idea back on the research agenda.

The sequence version arrived in 2014. Cho and colleagues introduced an RNN encoder-decoder for machine translation and used it to score phrase pairs. In the same year Sutskever, Vinyals and Le trained a large LSTM encoder-decoder end to end on English-to-French translation and showed it was competitive with phrase-based systems. Bahdanau, Cho and Bengio then pointed out that forcing the whole sentence through one vector was the main weakness, and added attention so the decoder could look back at every encoder state. Their work led directly to the Transformer in 2017, which keeps the encoder-decoder shape but builds both halves from attention alone.

In vision, the shape found a second home. Ronneberger and colleagues introduced U-Net in 2015 for segmenting biomedical images. Its skip connections carry fine detail past the bottleneck, and it became a default for pixel-level prediction. Diffusion and generative image models later reused the same encoder-decoder pattern inside their denoising networks.

Check yourself

QuestionRecall: what are the two parts of an encoder-decoder, and what joins them?Show answer

The encoder reads the input and produces a compact representation, and the decoder reads that representation and produces the output. They are joined by the bottleneck, the fixed-size code or context vector that carries everything the decoder knows about the input.

QuestionComputation: an encoder-decoder assigns probabilities 0.8, 0.6 and 0.9 to the three output steps of a target. What is the total probability and the negative log-likelihood in nats?Show answer

The total probability is the product: 0.8×0.6×0.9=0.4320.8 \times 0.6 \times 0.9 = 0.432. The negative log-likelihood is −ln⁡(0.432)-\ln(0.432). Since ln⁡(0.432)≈−0.839\ln(0.432) \approx -0.839, the loss is about 0.8390.839 nats.

QuestionWhy: why does the bottleneck force the network to keep only the important parts of the input?Show answer

The code has fewer numbers than the input, so it cannot store every detail. Training minimises the output error, so the encoder learns to keep whatever features best predict the target and to discard what does not. The size of the bottleneck sets how much can be kept.

QuestionApplied: you are building a model that labels every pixel of a 512 by 512 medical scan as tissue or background. Why would a plain encoder-decoder blur the boundaries, and what would you add?Show answer

Pixel labels need precise edges, but the bottleneck has compressed the image down to a coarse grid, so fine boundary detail is lost before the decoder runs. Adding skip connections from each encoder stage to the matching decoder stage, as in U-Net, passes that detail across the bottleneck and restores sharp boundaries.

Sources