The Architecture That Changed Everything

Transformer
Architecture

Discover the revolutionary neural network architecture that powers GPT, BERT, and modern AI. From attention mechanisms to multi-head magic.

2017
Year Introduced
170M
Original Parameters
175B
GPT-3 Parameters
∞
Possibilities
Scroll to explore
Core Architecture

The Transformer Encoder-Decoder

Understanding the building blocks of modern language models

Architecture Flow

9

Output Probabilities

8

Linear + Softmax

7

Decoder Stack (N×)

6

Feed Forward

5

Add & Norm

4

Multi-Head Attention

3

Add & Norm

2

Input Embedding

1

Positional Encoding

Why Transformers?

Parallelization

Process all tokens simultaneously, unlike RNNs

Long-range Dependencies

Attention connects any two positions directly

Transfer Learning

Pre-train once, fine-tune for any task

Key Innovation

"The Transformer relies entirely on attention mechanisms to draw global dependencies between input and output, dispensing with recurrence and convolutions entirely."

— Attention Is All You Need (Vaswani et al., 2017)

Input Representation

Token Embeddings & Position

How words become numbers that computers understand

Embedding Visualization

The
0
-0.70
0.89
0.55
0.82
0.85
-0.42
-0.91
0.65
transformer
1
-0.73
-0.97
0.46
-0.39
-0.56
0.61
-0.04
0.32
architecture
2
0.69
0.40
-0.19
-0.58
-0.34
-0.95
-0.37
0.39
revolutionized
3
0.53
-0.63
-0.67
-0.05
-0.83
0.17
-0.92
0.79
NLP
4
0.95
0.85
0.14
0.59
-0.02
0.65
-0.41
-0.47

How It Works

🔤

1. Tokenization

Text is split into tokens (words or subwords). Each token gets a unique ID.

📊

2. Embedding Lookup

Each token ID maps to a high-dimensional vector (typically 512-2048 dimensions) that captures semantic meaning.

📍

3. Positional Encoding

Since transformers process all tokens in parallel, we add position information using sine and cosine functions.

Positional Encoding Formula

# Even indices (2i)

PE(pos, 2i) = sin(pos / 10000^(2i/d_model))

# Odd indices (2i+1)

PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))

This allows the model to learn relative positions easily, as PE(pos+k) can be represented as a linear function of PE(pos).

Core Mechanism

Self-Attention

The heart of the transformer: allowing each token to attend to all other tokens

Attention Weights Matrix

The
cat
sat
on
the
mat
0.35
0.15
0.20
0.10
0.12
0.08
0.10
0.45
0.15
0.12
0.10
0.08
0.08
0.12
0.50
0.15
0.08
0.07
0.05
0.08
0.12
0.55
0.10
0.10
0.15
0.10
0.08
0.12
0.35
0.20
0.08
0.05
0.05
0.10
0.22
0.50

The attends to:

The
35%
cat
15%
sat
20%
on
10%
the
12%
mat
8%

Attention Formula

Attention(Q, K, V) = softmax(
QKT√dk
)V
QQuery matrix
KKey matrix
VValue matrix

How It Works

1
Create Q, K, V

Linear projections from input

2
Compute Scores

Q × KT for similarity

3
Scale & Softmax

Divide by √dk, then normalize

4
Weighted Sum

Multiply by V for output

Parallel Processing

Multi-Head Attention

Multiple attention heads working in parallel, each focusing on different aspects

Attention Heads

Output Concatenation

Concat → Linear

Why Multiple Heads?

🎯

Different Focus

Each head learns different relationships

🔍

Multiple Subspaces

Attend to information from different representation spaces

⚡

Ensemble Effect

Combined heads are more robust than single attention

🧠

Richer Context

Capture various types of dependencies simultaneously

Common Configurations

BERT-Base
12 heads64d per head
GPT-3
96 heads128d per head
LLaMA-2
32 heads128d per head
Position-wise Processing

Feed-Forward Network

The transformation applied to each position independently

FFN Architecture

Input (dmodel)
Expand (4×)
Output (dmodel)
FFN(x) = activation(xW₁ + b₁)W₂ + b₂

Activation Functions

-2.5
2.5
-2
-0.05
-1
-0.16
-0.5
-0.15
0
0.00
0.5
0.35
1
0.84
2
1.95

ReLU

f(x) = max(0, x)

Simple, fast, but can cause "dying ReLU"

GELU

Smoother alternative

Used in BERT, GPT. Smoother gradients

Implementation

Code Examples

Production-ready implementations in popular deep learning frameworks

1import torch
2import torch.nn as nn
3import math
4
5class MultiHeadAttention(nn.Module):
6 def __init__(self, d_model=512, num_heads=8):
7 super().__init__()
8 assert d_model % num_heads == 0
9
10 self.d_model = d_model
11 self.num_heads = num_heads
12 self.d_k = d_model // num_heads
13
14 # Linear projections
15 self.W_q = nn.Linear(d_model, d_model)
16 self.W_k = nn.Linear(d_model, d_model)
17 self.W_v = nn.Linear(d_model, d_model)
18 self.W_o = nn.Linear(d_model, d_model)
19
20 def scaled_dot_product_attention(self, Q, K, V, mask=None):
21 scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
22
23 if mask is not None:
24 scores = scores.masked_fill(mask == 0, -1e9)
25
26 attn_weights = torch.softmax(scores, dim=-1)
27 output = torch.matmul(attn_weights, V)
28 return output, attn_weights
29
30 def forward(self, query, key, value, mask=None):
31 batch_size = query.size(0)
32
33 # Linear projections and reshape
34 Q = self.W_q(query).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
35 K = self.W_k(key).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
36 V = self.W_v(value).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
37
38 # Apply attention
39 attn_output, attn_weights = self.scaled_dot_product_attention(Q, K, V, mask)
40
41 # Concatenate heads and apply final linear
42 attn_output = attn_output.transpose(1, 2).contiguous().view(
43 batch_size, -1, self.d_model
44 )
45 return self.W_o(attn_output)
46
47# Usage
48mha = MultiHeadAttention(d_model=512, num_heads=8)
49x = torch.randn(2, 100, 512) # (batch, seq_len, d_model)
50output = mha(x, x, x) # Self-attention
51print(f"Input shape: {x.shape}")
52print(f"Output shape: {output.shape}")
Interactive Demo

Attention Playground

Experiment with attention patterns in real-time

Configuration

18

Select Query Token

Attention Patterns for "The"

Head 1
The
34%
cat
25%
sat
15%
on
10%
the
11%
mat
5%
Head 2
The
35%
cat
22%
sat
17%
on
14%
the
10%
mat
3%
Head 3
The
40%
cat
25%
sat
17%
on
10%
the
8%
mat
0%
Head 4
The
43%
cat
25%
sat
19%
on
6%
the
5%
mat
2%

Combined Attention (Head 1)

The
cat
sat
on
the
mat
The
34
25
cat
20
28
20
sat
21
28
18
on
19
28
22
the
16
21
33
22
mat
19
20
36