Transformers

A transformer turns attention into a full architecture by adding position, feed-forward layers, residual paths, normalization, and stacked blocks.

The Big Question

Attention solved a major sequence-modeling problem: every token could look directly at every other token. The next question is architectural.

Can we build an entire neural network around attention?

The answer is the transformer. A transformer is not just attention. It combines self-attention with positional information, feed-forward networks, residual connections, layer normalization, and many repeated blocks.

The Remaining Problem

Attention lets tokens communicate directly, but attention alone does not know word order. The sentences below contain the same words but mean very different things:

Jessie ate the burger.
The burger ate Jessie.

A transformer needs both direct token-to-token communication and information about position.

Core Intuition

Think of a transformer layer as a meeting. Every token enters with its own meaning. Through self-attention, each token listens to the other tokens it finds relevant. Then a small neural network processes the updated meaning of each token.

After one layer, every token is more contextual. After many layers, each token has absorbed increasingly rich information from the whole sequence.

The Transformer Block

Token embeddingsConvert tokens into vectors
Positional informationTell attention where tokens appear
Multi-head self-attentionMix information across tokens
Residual connectionAdd the original signal back
Layer normalizationStabilize representation scale
Feed-forward networkTransform each token independently
Stacked layersRepeat the block to build richer representations

Attention mixes information between tokens. The feed-forward network transforms each token representation after that mixing. Residual connections and normalization keep the stack trainable.

Interactive Demo

Transformer block explorer

One transformer block

Token representations

Jessie
position 1
ordered
position 2
a
position 3
burger
position 4
queryJessieorderedaburger
Jessie0.420.280.080.22
ordered0.350.080.060.51
a0.080.120.120.68
burger0.180.460.060.30
Selected component
Mix information across tokens

Self-attention lets each token retrieve relevant context from every other allowed token.

Attention versus transformer

Attention is the token-mixing operation. A transformer block wraps attention with positional information, feed-forward networks, residual paths, and normalization.

Causal masking

Decoder-only language models must not look at future tokens during training. Turn on the mask to block attention to positions on the right.

Order matters

Without positional information, self-attention knows which tokens are present but not where they appear. That is why position is added before attention.

Toggle positional information and causal masking. Click the block components to see how attention becomes a full transformer layer.

Mathematics And Architecture

Token Embeddings

Text first becomes tokens, and each token becomes a vector:

xiRdmodelx_i\in\mathbb{R}^{d_{\text{model}}}

A sequence of nn tokens becomes a matrix:

XRn×dmodelX\in\mathbb{R}^{n\times d_{\text{model}}}

Positional Encoding

Self-attention needs position information. The simplest view is that each token embedding receives a position vector:

xi=xi+pix_i'=x_i+p_i

Common choices include fixed sinusoidal positional encodings, learned positional embeddings, and rotary positional embeddings in many modern language models.

Self-Attention

Each token representation is projected into queries, keys, and values:

Q=XWQ,K=XWK,V=XWVQ=XW_Q,\qquad K=XW_K,\qquad V=XW_V

The attention operation is:

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q,K,V)=\text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

This produces contextual token representations. For example, ordered can attend to Jessie and burger so its representation includes who did the ordering and what was ordered.

Multi-Head Attention

Language contains many relationships at once: subject to verb, adjective to noun, pronoun to noun, cause to effect, and instruction to answer. Multi-head attention runs several attention mechanisms in parallel so different heads can learn different relationships.

Each head has its own query, key, and value projections. The head outputs are concatenated and projected back to the model dimension.

Feed-Forward Network

After attention mixes information across tokens, a small neural network transforms each token independently:

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

This distinction matters: attention mixes across tokens, while the feed-forward network processes each token's updated representation.

Residual Connections

Deep networks are easier to train when layers learn corrections:

y=x+f(x)y=x+f(x)

The shortcut lets information and gradients flow through the network. If a layer is not useful yet, the model can keep the original representation and add only a small change.

Layer Normalization

As representations move through many layers, their scale can become unstable. Layer normalization stabilizes each token representation by normalizing across its feature dimension.

The intuition is simple: keep activations in a reasonable range so optimization does not spiral out of control.

Encoder, Decoder, And Causal Masking

TypeExampleUsed for
Encoder-onlyBERT-style modelsclassification, semantic search, embeddings
Decoder-onlyGPT-style modelsnext-token generation
Encoder-decoderOriginal translation transformersequence-to-sequence tasks

Decoder-only transformers use causal masking. When predicting the next token, a token can attend only to itself and earlier tokens, not future tokens.

Why Transformers Beat RNNs

  • They process all tokens in parallel during training.
  • Any token can directly attend to any other token.
  • Stacked attention layers learn rich contextual representations.

Computational Cost

Full self-attention compares every token with every other token. For sequence length nn, the attention matrix has n×nn\times n entries:

O(n2)O(n^2)

This quadratic scaling is why long context windows are expensive.

Implementation

This is a tiny decoder-style transformer block. It includes self-attention, a causal mask, residual connections, layer normalization, and a feed-forward network.

import torch
from torch import nn

class TransformerBlock(nn.Module):
    def __init__(self, d_model, num_heads, d_ff):
        super().__init__()
        self.attn = nn.MultiheadAttention(
            embed_dim=d_model,
            num_heads=num_heads,
            batch_first=True,
        )
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.ffn = nn.Sequential(
            nn.Linear(d_model, d_ff),
            nn.GELU(),
            nn.Linear(d_ff, d_model),
        )

    def forward(self, x):
        seq_len = x.size(1)
        mask = torch.triu(
            torch.ones(seq_len, seq_len, device=x.device),
            diagonal=1,
        ).bool()

        attn_out, attn_weights = self.attn(
            x,
            x,
            x,
            attn_mask=mask,
            need_weights=True,
        )
        x = self.norm1(x + attn_out)

        ffn_out = self.ffn(x)
        x = self.norm2(x + ffn_out)
        return x, attn_weights

block = TransformerBlock(d_model=64, num_heads=4, d_ff=256)
tokens = torch.randn(8, 12, 64)
output, weights = block(tokens)

print(output.shape)   # (8, 12, 64)
print(weights.shape)  # attention matrix

A full language model stacks many of these blocks, adds token and positional embeddings before them, and adds an output layer that predicts the next token.

Interview Discussion

What problem did transformers solve compared with RNNs?

They removed sequential recurrence, allowing tokens to communicate directly through attention and be processed in parallel during training.

Why does self-attention need positional information?

Attention alone knows which tokens are present but not their order, so position information is needed to distinguish sentences with the same words in different orders.

What does multi-head attention do?

It runs several attention mechanisms in parallel so different heads can learn different relationships.

What does the feed-forward network do inside a transformer block?

It transforms each token representation independently after attention has mixed information across tokens.

Why are residual connections important?

They create shortcut paths for information and gradients, making deep transformer stacks easier to train.

What is causal masking?

It blocks a token from attending to future tokens, preserving the next-token prediction setup.

Why does attention become expensive for long sequences?

Every token compares with every other token, so the attention matrix grows quadratically with sequence length.

Active Recall

1. Explain the difference between attention and a transformer.

2. Why does a transformer need positional information?

3. What does attention do inside a transformer block?

4. What does the feed-forward network do after attention?

5. Why are residual connections and layer normalization useful?

6. What is the difference between encoder-only and decoder-only transformers?

7. Why are GPT-style models decoder-only?

8. Why is attention cost O(n squared)?

Common Mistakes

  • Thinking transformer means attention only.
  • Forgetting that attention alone has no order information.
  • Confusing encoder-only, decoder-only, and encoder-decoder models.
  • Treating causal masking as optional for next-token prediction.
  • Assuming feed-forward layers mix information across tokens.
  • Ignoring the quadratic cost of full self-attention.

Connection To Transformer as a Language Model

This completes the Deep Learning arc: from one artificial neuron to the transformer. The next section asks how a transformer becomes a language model through next-token prediction, tokenization, pretraining, scaling, alignment, and decoding.