Transformer (Neural Network Architecture) — What It Is and How It Works | AI Terms Guide
Category: ArchitectureDifficulty: IntermediateFirst appeared: 2017Last updated: Aug 6, 2026

Transformer (neural network architecture)

The Transformer is the neural network architecture behind every modern large language model — including Claude, GPT, Gemini, and Llama.
Introduced by Vaswani et al. in the 2017 paper Attention Is All You Need, the Transformer replaced sequential architectures like RNNs and LSTMs by processing entire sequences in parallel through the self-attention mechanism. This parallelism made it possible to train models orders of magnitude larger than anything before — enabling the entire era of large language models.

At a glance

Also known as
Transformer Architecture
Category
Deep Learning Architecture
First widely used
2017 (Vaswani et al.)
Difficulty
Intermediate

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.

PYTHON
# 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 x
Notice: This is a simplified block. Real production LLMs also use techniques like RoPE positional encoding, RMSNorm instead of LayerNorm, and grouped-query attention for efficiency.

When 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

1

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.

2

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.

3

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.

4

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.

5

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.

6

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.

7

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.

Transformer block (simplified) Input Embeddings + Positional Encoding Multi-Head Self-Attention Add & Layer Norm (residual connection) Feed-Forward Network (MLP) Repeated N times (N = 12-96+ in modern LLMs)
A simplified transformer block. Modern LLMs stack 12–96+ of these blocks with variations like RoPE, RMSNorm, and Mixture of Experts.

Common misconceptions

Misconception #1: Transformers only work on text.
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.
Misconception #2: Bigger transformers are always better.
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.
Misconception #3: Transformers 'understand' language the way humans do.
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.

Where you'll see this in practice

Learn more

Sources & further reading

  1. Attention Is All You Need — Vaswani et al., 2017 (NeurIPS). Read →
  2. The Illustrated Transformer — Jay Alammar, 2018 (widely-referenced visual explainer). Read →
  3. The Annotated Transformer — Sasha Rush et al., Harvard NLP. Read →
  4. Training Compute-Optimal Large Language Models — Hoffmann et al., 2022 (Chinchilla). Read →
FAQ

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.

Share with