Encoder-Decoder Transformer Architectures

Transformers are built from two fundamental computational blocks called encoders and decoders, which can be composed in different ways to produce distinct model families. These blocks differ in their attention structure and the type of information they are designed to model.

An encoder is a stack of transformer layers that applies bidirectional self-attention to an input sequence. Given embeddings an encoder layer computes

with layer normalization applied around each block. Encoders learn bidirectional, content-dependent representations of the entire input . They are not autoregressive and do not generate tokens.

A decoder is a transformer stack designed for auto-regressive generation, using masked self-attention so that each position only attends to earlier ones, such that for all tokens (implemented by adding to the logits above the diagonal before softmax). Masked self-attention ensures that the decoder does not “cheat” during training by peeking into future tokens. Given a partially generated sequence , a decoder layer computes

where is cross-attention, which conditions the decoder on the encoder’s output. In cross-attention, queries come from the decoder while keys and values come from the encoder:


where are the top-layer encoder outputs and are the current decoder hidden states. The attention scores and output follow the same scaled dot-product formula as self-attention, but over an (decoder-by-encoder) matrix rather than . Cross-attention is the only component where the input and output sequences interact. LayerNorm is applied around each block.

Encoders and decoders can be used in tandem to design different transformer model families:

  • Autoencoding Transformers consist of only an encoder and learn contextual representations through reconstruction or denoising objectives, such as
  • Autoregressive Transformers consist of only a decoder with masked self-attention. The mask ensures a strict left-to-right factorization; cross-attention is absent. The model is fully generative (e.g., GPT, Mistral, LLaMA).
  • Sequence-to-Sequence (Seq2Seq) Transformers combine an encoder and a decoder. The encoder produces contextual representations H; the decoder autoregressively generates while attending to via cross-attention. This provides a clean separation between understanding the input and generating the output. The model is also fully generative (e.g., T5, BART, original transformer).