Transformer (neural network architecture)
At a glance
Definition
A Transformer is a neural network architecture designed to process sequential data — text, code, audio, or images treated as sequences of patches — by using an attention mechanism to weigh the importance of different positions in the input. Unlike earlier architectures such as RNNs and LSTMs that process sequences one element at a time, Transformers process the entire input in parallel — dramatically speeding up training and enabling the scale of modern models.
The original Transformer, published in the paper Attention Is All You Need, was designed for machine translation. It used an encoder-decoder architecture with six layers each, roughly 65 million parameters, and outperformed the state of the art on English-German and English-French translation. What made the paper revolutionary was the claim in its title: attention, without recurrence or convolution, was sufficient to build a state-of-the-art model.
Since 2018, essentially all frontier language models — Claude, GPT, Gemini, Llama, Mistral, DeepSeek, and Qwen — are Transformer variants. Modern LLMs typically use a decoder-only variant with dozens or hundreds of layers and billions to trillions of parameters. Transformers have also been adapted for images (Vision Transformer), audio (Whisper), and multimodal understanding.
The three core innovations that make Transformers work are: (1) self-attention, which lets every position in a sequence look at every other position; (2) positional encoding, which adds order information since attention itself is order-invariant; and (3) parallelization, which lets the entire sequence be processed at once on GPUs. Combined, these turn what used to take days into hours — and what used to be impossible into achievable.
Real-world example
How a Transformer processes "The cat sat on the mat"
When you send a message to Claude or ChatGPT, the transformer inside first breaks your text into tokens, converts each token into a numeric vector (an embedding), and adds positional information so the model knows the order. Then, layer by layer, self-attention lets every token 'look at' every other token to build up a rich contextual understanding. By the final layer, the model has computed a probability distribution over what token should come next — which is how the response is generated, one token at a time.
# Simplified transformer block in PyTorch
import torch
import torch.nn as nn
class TransformerBlock(nn.Module):
def __init__(self, d_model=512, n_heads=8):
super().__init__()
self.attention = nn.MultiheadAttention(d_model, n_heads)
self.norm1 = nn.LayerNorm(d_model)
self.ffn = nn.Sequential(
nn.Linear(d_model, d_model * 4),
nn.GELU(),
nn.Linear(d_model * 4, d_model),
)
self.norm2 = nn.LayerNorm(d_model)
def forward(self, x):
# 1. Self-attention with residual + norm
attn_out, _ = self.attention(x, x, x)
x = self.norm1(x + attn_out)
# 2. Feed-forward with residual + norm
x = self.norm2(x + self.ffn(x))
return xWhen you'll encounter this
- You're using any modern LLM — Claude, GPT-5, Gemini, Llama — you're using a Transformer under the hood.
- You're reading AI research papers — architecture papers assume you know how Transformers work.
- You're fine-tuning models — understanding attention and layer structure guides LoRA configuration.
- You're debugging performance — the quadratic cost of self-attention shapes context window limits and inference cost.
- You're designing prompts for long contexts — the 'lost in the middle' phenomenon is a consequence of how attention learns.
How it works
Input tokenization
Text is broken into tokens (roughly 3-4 characters or 0.75 words in English) by a tokenizer. Each token gets a unique integer ID.
Embedding + positional encoding
Each token ID is mapped to a dense vector (usually 512-4096 dimensions). Positional information is added so the model knows the order — either via learned positional encodings or modern methods like RoPE.
Multi-head self-attention
For each token, the model computes queries, keys, and values. Attention weights (softmax of query·key) determine how much each token attends to every other. Multiple 'heads' let the model attend to different things in parallel.
Residual + normalize
The attention output is added to the input (residual connection) and normalized (LayerNorm or RMSNorm). This stabilizes training and lets the model build up features gradually.
Feed-forward network
Each position independently passes through a two-layer feed-forward network (typically 4x the model dimension). This is where much of the model's stored knowledge lives.
Repeat N times
The whole block is repeated 12-96+ times, each layer building richer representations. In modern LLMs, some layers use Mixture of Experts instead of dense feed-forward.
Output projection
The final layer's output for each position is projected back to vocabulary size. Softmax gives probabilities for the next token. In decoder-only LLMs, you sample from this distribution to generate one token, then repeat.
Common misconceptions
Transformers work on any data that can be tokenized into a sequence. Vision Transformers treat 16×16 image patches as tokens. Whisper uses transformers for audio. AlphaFold uses them for protein structures. The architecture is agnostic to modality.
Not exactly. Model quality scales with a combination of parameters, training data, and compute — the Chinchilla scaling laws showed that many earlier models were undertrained. Bigger models require proportionally more data to reach their potential. Sometimes a well-trained smaller model outperforms a larger under-trained one.
Transformers are extraordinarily good at pattern matching over their training data. Whether that constitutes understanding is a deep philosophical and empirical question. What we can say for certain: they're statistical machines that predict tokens well enough to be genuinely useful across a huge range of tasks.
Related terms
Related in Deep Learning Architectures
Broader concepts
Narrower / specific concepts
Head-to-head comparisons
Where you'll see this in practice
Related tools
Related models
Learn more
- Read the deep-dive: How Transformers Work
- Start the AI for Developers learning path
- Compare Transformer vs Mamba architectures
- Browse the Deep Learning Architectures category
Sources & further reading
- Attention Is All You Need — Vaswani et al., 2017 (NeurIPS). Read →
- The Illustrated Transformer — Jay Alammar, 2018 (widely-referenced visual explainer). Read →
- The Annotated Transformer — Sasha Rush et al., Harvard NLP. Read →
- Training Compute-Optimal Large Language Models — Hoffmann et al., 2022 (Chinchilla). Read →
Frequently asked about Transformer
The Transformer was introduced in the 2017 paper Attention Is All You Need by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan Gomez, Łukasz Kaiser, and Illia Polosukhin — a team primarily at Google Brain and Google Research. The paper was published at NeurIPS 2017 and has since become the most cited paper of the deep learning era.
Alternatives like Mamba and State Space Models are showing strong results with better scaling properties for long context. Hybrid architectures (like Jamba) combine transformers with SSMs. But transformers still dominate production LLMs in 2026 due to years of infrastructure investment and their proven track record. Full replacement, if it comes, will take years.
The original 2017 Transformer used encoder-decoder architecture for translation with ~65M parameters. Modern LLMs (Claude, GPT-5, Gemini) use decoder-only architecture with hundreds of billions to trillions of parameters, RoPE positional encoding instead of learned embeddings, RMSNorm instead of LayerNorm, and often Mixture of Experts instead of dense feed-forward. The core idea — attention-based sequence processing — remains identical.
For a sequence of N tokens, self-attention computes an N×N attention matrix — every token attending to every other. That's N² comparisons. This is why context windows are expensive: doubling context length quadruples attention cost. Optimizations like FlashAttention, sliding window attention, and grouped-query attention reduce the practical cost but don't change the fundamental complexity.
Not deeply. Understanding the high-level concepts — attention, context window, positional encoding — helps you write better prompts and reason about model behavior. For most API users, our How Transformers Work tutorial provides more than enough depth. Fine-tuners and researchers benefit from deeper study.
Technically reviewed by the AI Terms Guide editorial team on August 6, 2026. Last updated: August 6, 2026. Spotted an error? Let us know — corrections ship within 24 hours.
Building with AI? Try our sister sites
Deep coverage of AI errors, code patterns, and pricing you won't find in the reference.
AI Terms Weekly
One deep term, three new models, one comparison — every Tuesday.