Artificial Intelligence • Generative AI and Language Models • 15 min read

The Transformer Architecture

A Transformer is a neural network architecture designed to process sequences by using attention mechanisms to exchange information between positions. Introduced in the 2017 paper Attention Is All You Need, the original Transformer combined an encoder and a decoder and replaced recurrent sequence-processing layers with attention-based computation.

Transformers are foundational to many modern language models. Variants also process images, audio, biological sequences, and combinations of data types. Their importance comes from the way they learn contextual representations, support parallel computation during training, and scale to large datasets and model sizes.

To understand a Transformer, distinguish its architecture (how computations are connected) from a model (a particular network with learned parameter values), a training objective (what it learns to predict), and a system (the software that uses it). These are related, but they are not interchangeable.

Start with a simple example

Read these two sentences: “The bank approved the loan” and “The boat reached the bank.” The word bank changes meaning depending on nearby words. A useful language model needs a way to let each token incorporate information from the rest of its context.

A Transformer does this primarily through attention. For each position, the model forms learned representations that help it decide which other positions to draw information from. It then combines information, applies additional transformations, and repeats this through multiple layers.

A simplified path through a Transformer is:

  1. Turn text into tokens, then numerical embeddings.
  2. Add or otherwise incorporate information about token positions.
  3. Use attention to exchange information across positions, respecting the model’s attention mask.
  4. Transform each position using feed-forward layers, with residual connections and normalization.
  5. Produce representations used for the model’s task, such as predicting a next token or classifying an input.

Important distinction: A Transformer is an architecture, not a synonym for a chatbot or an LLM. Encoder-only, decoder-only, and encoder–decoder models use related components but differ in how information flows and what tasks they are designed to perform.

1. The problem Transformers address

Language is sequential, but the meaning of a word depends on context. In the sentences “the bank approved the loan” and “the boat approached the bank,” the word bank has different meanings. A language model needs a way to use surrounding words when constructing a representation of each token.

Earlier sequence architectures such as recurrent neural networks process information through recurrent hidden states. Transformers instead use attention to allow sequence positions to obtain information from other relevant positions. For a full-attention encoder, positions can attend across the input sequence in a single attention layer; a causal decoder is restricted to positions available at generation time.

This design offers several advantages:

  • Context-dependent representations: A token can combine information from other tokens.
  • Parallel sequence computations in training: Unlike strictly recurrent processing, many token positions can be handled simultaneously when the complete training sequence is available.
  • Flexible architecture: Encoder-only, decoder-only, and encoder-decoder designs suit different tasks.
  • Scalability: Larger models, longer training, and specialized hardware can be used effectively, although memory and compute costs remain significant.

Attention is not a guarantee of perfect reasoning or factual correctness. It is a learned computation that mixes information, not an explicit symbolic proof system.

2. The Transformer processing pipeline

Consider a short input: “The cat sleeps.” A simplified Transformer pipeline consists of the following stages.

  1. Tokenization: Convert the text into token IDs using a model-specific tokenizer.
  2. Embedding: Look up a learned vector for each token ID.
  3. Position information: Incorporate ordering information so tokens are not treated as an unordered set.
  4. Transformer blocks: Repeatedly compute attention-based interactions and feed-forward transformations.
  5. Task-specific output: Produce token representations, classification scores, or a distribution over next-token candidates.
Simplified Transformer pipeline from text tokens through embeddings, positional information, attention blocks, and output predictions
The common processing stages of a Transformer-based model. The output and attention masks depend on the specific architecture and task.

This figure shows a simplified flow, not the internal wiring of every Transformer. In an encoder-decoder model, the decoder also uses information provided by the encoder.

3. Tokens and embeddings

A tokenizer converts text into discrete units called tokens. A token may correspond to a word, punctuation, a word fragment, or another unit selected by the tokenizer.

For example, a tokenizer might represent “unbelievable” as a single token or several subword tokens. There is no universal tokenization shared by all Transformer models.

Each token ID is mapped to a learned numerical vector called a token embedding. If there are nn tokens and the model hidden dimension is dmodeld_{\mathrm{model}}, the initial sequence representation can be written as a matrix:

X∈Rn×dmodel.X \in \mathbb{R}^{n \times d_{\mathrm{model}}}.

Each row holds a representation of one token position. The rows are updated repeatedly by the Transformer layers, so later layers encode more contextual information than the initial lookup vectors.

The embedding dimension is not the vocabulary size. The vocabulary size is the number of distinct token IDs the model can recognize; the hidden dimension is the width of the internal vectors.

See Text Processing, Tokenization, and Embeddings for the underlying representations.

4. How a Transformer represents position

Self-attention alone does not inherently specify token order: without position information, it treats a permutation of input positions correspondingly. But “dog bites person” and “person bites dog” should not have identical interpretations.

Transformers therefore incorporate positional information. Common approaches include:

  • Absolute positional encodings: Add or otherwise introduce a representation associated with a position.
  • Learned positional embeddings: Learn position-related vectors during training.
  • Relative position methods: Represent relationships between token positions inside attention computations.
  • Rotary position embeddings (RoPE): Transform attention query and key vectors in a position-dependent way, enabling relative-position interactions.

The original 2017 Transformer used sinusoidal positional encodings. Many later architectures use different methods. Positional handling affects generalization to longer sequences and the costs and behavior of attention, but no positional scheme removes all context-length limitations.

5. Self-attention: exchanging information between tokens

Self-attention is a mechanism through which each token position constructs a new representation using information from token positions in the same sequence. It does so by computing relevance scores and using them to weight information from other positions.

From a sequence representation XX, learned linear projections produce three matrices:

Q=XWQ,K=XWK,V=XWV.Q=XW_Q,\qquad K=XW_K,\qquad V=XW_V.
  • Queries (QQ): Represent what a token position is seeking.
  • Keys (KK): Represent what each position makes available for matching.
  • Values (VV): Carry information combined into the output.

A common attention computation is scaled dot-product attention:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk+M)V.\operatorname{Attention}(Q,K,V) =\operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V.

Here dkd_k is the key-vector dimension and MM is an optional attention mask or bias. Masked-out positions receive a sufficiently negative score so their softmax weights are effectively zero.

The process has four conceptual steps:

  1. Compare each query with the keys to obtain scores.
  2. Scale the scores by dk\sqrt{d_k} to help control their magnitude.
  3. Apply the mask when required and normalize scores with softmax.
  4. Use the resulting weights to combine the value vectors.

The attention weights describe how information is mixed in this computation. They should not be treated as a complete explanation of a model’s reasoning or a reliable measure of causal importance.

Bidirectional and causal attention

Bidirectional self-attention allows a token position to use other positions on both sides of the input, subject to padding or task-specific masks. It is common in encoder models.

Causal self-attention prevents a position from attending to later positions. A decoder using next-token prediction can therefore model a sequence without gaining access to future target tokens during training.

For three token positions, a causal visibility pattern looks like this:

Query positionMay attend to
Token 1Token 1
Token 2Tokens 1 and 2
Token 3Tokens 1, 2, and 3

This constraint matters: without it, a next-token training objective could leak the answer from later positions.

The mathematical details and a worked attention example belong to Attention, Self-Attention, and Multi-Head Attention.

6. Multi-head attention

A Transformer normally uses multi-head attention rather than a single attention calculation. Multiple heads learn different sets of query, key, and value projections and compute separate attention outputs.

The outputs are concatenated and projected back to the model’s hidden dimension:

MultiHead⁡(X)=Concat⁡(h1,…,hH)WO,\operatorname{MultiHead}(X) =\operatorname{Concat}(h_1,\ldots,h_H)W_O,

where HH is the number of heads and each hih_i is the result of one attention head.

Different heads can learn different patterns, such as local relationships or long-range dependencies, but their precise roles are not guaranteed or fixed in advance.

Some modern implementations share key and value representations across groups of query heads to reduce memory requirements during inference. Such optimizations preserve the broad Transformer design while changing details of the attention computation.

7. Feed-forward networks, residual connections, and normalization

Attention is only part of a Transformer block. A typical block also includes a position-wise feed-forward network, which applies the same learned transformation separately to each token’s vector after attention-based mixing.

A simple feed-forward network can be written as:

FFN⁡(x)=W2 σ(W1x+b1)+b2,\operatorname{FFN}(x)=W_2\,\sigma(W_1x+b_1)+b_2,

where σ\sigma is a nonlinear activation function. Actual models may use GELU, gated activations, or other variants.

The remaining block components are equally important:

  • Residual connections: Add a block’s input to a transformed output, supporting information and gradient flow through deep networks.
  • Layer normalization: Normalizes features within a token representation to help stabilize computation and training.
  • Dropout: May be used during training to regularize activations, although its use varies by model.

Architectures differ in pre-normalization and post-normalization placement. The original Transformer used a post-normalization pattern; many later large models use pre-normalization or related variants.

A conceptual pre-normalization block is:

H=X+Attention⁡(LayerNorm⁡(X)),H=X+\operatorname{Attention}(\operatorname{LayerNorm}(X)), Y=H+FFN⁡(LayerNorm⁡(H)).Y=H+\operatorname{FFN}(\operatorname{LayerNorm}(H)).

These expressions omit attention masks, multi-head projections, and other implementation details for clarity.

8. Encoder-only, decoder-only, and encoder-decoder architectures

Not every Transformer has the same arrangement of components. Three broad designs are particularly important.

ArchitectureMain attention patternTypical strengthsExample model family
Encoder-onlyOften bidirectional self-attentionUnderstanding and representing an inputBERT
Decoder-onlyCausal self-attentionAutoregressive text generationGPT-style language models
Encoder-decoderEncoder self-attention, decoder causal self-attention, and cross-attentionTransforming one sequence into anotherOriginal Transformer, T5

Encoder-only models

An encoder processes an input sequence and produces context-aware representations. For tasks such as classification, these representations can feed a classification head. For token-level tagging, outputs can be generated at individual token positions.

Because an encoder can often attend to both earlier and later input tokens, it is well suited to analyzing text already available in full. The particular training objective still determines what the model learns.

Decoder-only models

A decoder-only model repeatedly predicts a continuation using the tokens available so far. During training, causal masking lets many target positions be evaluated in parallel, even though each position is not allowed to inspect later tokens.

At inference, generating a sequence usually remains autoregressive: the next token depends on previously generated tokens. Techniques such as key-value caching reduce repeated computation over prior tokens, but do not eliminate the sequential dependency of ordinary token-by-token generation.

Encoder-decoder models

An encoder-decoder Transformer first represents a source sequence using an encoder. Its decoder generates the output sequence while using:

  1. Causal self-attention over output tokens generated so far.
  2. Cross-attention over representations produced by the encoder.

Cross-attention differs from self-attention because queries can come from one sequence while keys and values come from another. This is useful for tasks such as translation, where the model reads an input sentence and generates a corresponding sentence in another language.

Encoder-decoder Transformer with source tokens entering the encoder and target tokens entering the decoder; encoder outputs feed decoder cross-attention
The original encoder-decoder arrangement. Decoder queries attend to the encoder's representations through cross-attention.

9. Training a Transformer

Transformer training adjusts parameters to reduce an objective function. The objective depends on the task and architecture.

For autoregressive language modeling, the model predicts the next token from the preceding tokens. For tokens x1,…,xTx_1,\ldots,x_T, a common negative log-likelihood loss is:

L(θ)=−∑t=1Tlog⁡pθ(xt∣x<t).\mathcal{L}(\theta) =-\sum_{t=1}^{T}\log p_\theta(x_t\mid x_{<t}).

Here x<tx_{<t} denotes earlier tokens. The training procedure typically:

  1. Selects and tokenizes training sequences.
  2. Constructs token embeddings and the appropriate attention masks.
  3. Runs a forward pass to produce predictions.
  4. Calculates loss against target tokens.
  5. Computes gradients using backpropagation.
  6. Updates learned parameters with an optimizer.

Encoder models may instead train by predicting masked or corrupted tokens. Encoder-decoder models may learn to generate target text conditioned on source text. The architecture alone does not define the training objective.

A model’s quality depends on training data, objective, optimization, scale, evaluation, and further adaptation. Being a Transformer does not inherently make a model truthful, unbiased, or safe.

For foundational training mechanics, see Forward Propagation and Backpropagation and Training Neural Networks.

10. A minimal Transformer example in PyTorch

The following example shows the shapes and flow of a small encoder. It is randomly initialized, so its outputs are not meaningful language representations until training occurs.

import torch
from torch import nn

# Batch of 2 sequences, each containing 4 token IDs.
token_ids = torch.tensor([
    [4, 7, 9, 2],
    [8, 3, 1, 5],
])

vocab_size = 20
hidden_size = 16
max_length = 8

embedding = nn.Embedding(vocab_size, hidden_size)
position_embedding = nn.Embedding(max_length, hidden_size)

layer = nn.TransformerEncoderLayer(
    d_model=hidden_size,
    nhead=4,
    dim_feedforward=32,
    batch_first=True,
)
encoder = nn.TransformerEncoder(layer, num_layers=2)

positions = torch.arange(token_ids.size(1)).unsqueeze(0)
x = embedding(token_ids) + position_embedding(positions)
output = encoder(x)

print("Input shape:", tuple(token_ids.shape))
print("Embeddings shape:", tuple(x.shape))
print("Encoder output shape:", tuple(output.shape))

Expected shapes:

Input shape: (2, 4)
Embeddings shape: (2, 4, 16)
Encoder output shape: (2, 4, 16)

The encoder produces one vector for each token position. A downstream task could use a pooling operation or an additional output head to convert these vectors into classification scores.

Important: This example adds learned absolute positions, does not handle padding, and does not train the encoder. Real implementations need appropriate masks, a task-specific loss, a training loop, evaluation, and model versioning. For causal generation, use a decoder-style model with causal attention rather than treating this bidirectional encoder as a ready-made next-token generator.

11. Computational cost and practical limitations

Transformers are powerful, but their resource requirements are significant.

Attention and sequence length

Standard full self-attention computes interactions between pairs of sequence positions. With sequence length nn, its attention-score matrix contains n2n^2 entries per head. This motivates the commonly cited quadratic dependence on sequence length for standard attention-score computation and storage in straightforward implementations.

The complete runtime also depends on hidden dimensions, projection operations, hardware, and implementation. Optimized attention kernels can avoid explicitly materializing the entire score matrix, reducing memory use without eliminating all computational costs.

Context windows

A model’s context window limits how much input and generated context it can process in a given configuration. Even within that window, performance on distant or competing information may be imperfect. Longer context does not guarantee faithful use of every token.

Generation latency

Autoregressive decoding produces new tokens conditionally on earlier tokens. This can create noticeable latency for lengthy outputs. Key-value caches, batching, quantization, and optimized inference engines help reduce cost, but introduce their own engineering trade-offs.

Reliability and safety

A Transformer trained for plausible text generation can produce unsupported claims, repeat biased patterns, or behave poorly on unfamiliar inputs. Applications therefore require evaluation, grounding when needed, access controls, and safeguards appropriate to the task.

12. Common misconceptions

“A Transformer is the same as a large language model.” A Transformer is an architecture; an LLM is a trained language model that may use a Transformer architecture.

“Attention reads the entire Internet while answering.” Attention operates on representations available to the model during its current computation. External data access requires separate retrieval or tools.

“All Transformers use the original encoder-decoder structure.” Modern Transformer-based models include encoder-only, decoder-only, and encoder-decoder variants.

“The model understands token order automatically.” Transformers need a means of representing position or order; the mechanism varies by design.

“Parallel training means all generation is parallel.” Many training calculations can be parallelized across positions, but ordinary autoregressive generation retains a sequential dependency.

13. Connections to other PlainCS concepts

Some linked articles are planned in the AI Knowledge Map and may not yet be published.

References and further reading

  1. Vaswani, A., et al. (2017). Attention Is All You Need. arXiv:1706.03762.
  2. Devlin, J., et al. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. arXiv:1810.04805.
  3. Raffel, C., et al. (2019). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. arXiv:1910.10683.
  4. Su, J., et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv:2104.09864.
  5. Dao, T., et al. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135.
  6. PyTorch documentation. TransformerEncoderLayer.

Related articles in

Image preview

Fit