Skip to main content
LearnMLAcademy
Advanced10 min read

Transformers for Deep Learning

Construct Transformer encoder and decoder stacks with positional encodings, with sequence diagrams, attention calculations, and model-code exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Deep Learning · Sequence Models

Study the Transformer as an architecture: self-attention, Q, K and V, position information, multiple heads, residual paths, normalization, feed-forward blocks, masks and encoder–decoder families.

Start From the Attention You Already Know

The previous lesson introduced attention. The Transformer makes attention the main mechanism for exchanging information across a sequence.

For each token representation x, learned projections create q=xWQ, k=xWK and v=xWV. A query describes what the current position needs, a key describes what another position offers, and a value carries the information that may be retrieved.

Query (Q)

What information is this position looking for?

Key (K)

How should this position be matched?

Value (V)

What information should be passed onward?

Attention(Q,K,V) = softmax(QKᵀ / √dk)V

For a sequence of tokens, QKᵀ forms an attention-score matrix: row i records how query i matches every key. Scaling controls score magnitude, softmax turns each row into weights, and multiplying by V gives one weighted value mixture per row.

Self-Attention and Cross-Attention Ask Different Questions

Attention typeQueries come fromKeys and values come fromWhat it enables
Encoder self-attentionSource sequenceThe same source sequenceEach source token learns source context
Masked decoder self-attentionCurrent target positionsAllowed earlier target positionsEach target position uses only known target context
Cross-attentionDecoder statesEncoder source representationsA target token retrieves relevant source information

The word self means Q, K and V originate from the same sequence representation—not that each token can attend only to itself. Cross means one sequence queries a different sequence.

A Transformer Removes the Recurrent Step-by-Step Encoder

A recurrent encoder must calculate h₁ before h₂. A Transformer encoder instead uses self-attention to connect positions and can process all source positions in parallel during training. Each block combines attention, a position-wise feed-forward network, residual shortcuts and normalization.

The original Transformer is an encoder–decoder built from attention blocks

Encoder stack

1. Input embedding + position

token identity and order

2. Self-attention

source tokens exchange context

3. Add, norm and feed-forward

refine each representation

repeated N layers

keys & values

→

cross-attention bridge

Decoder stack

1. Shifted target + position

known output tokens

2. Masked self-attention

cannot see future targets

3. Cross-attention

read encoder representations

4. Add, norm and feed-forward

refine decoder states

5. Linear + softmax

next-token probabilities

one distribution per target position

Residual shortcuts wrap the attention and feed-forward sublayers, while normalization stabilizes representations. The diagram groups those details to keep the information paths visible.

Multi-head attention repeats attention using different learned projections. Each head has an opportunity to model different relationships; their outputs are concatenated and projected. Heads are not assigned human labels, so saying one head “is grammar” is an interpretation to test, not a guarantee.

Where head dimensions come from

Suppose the developer chooses model width dmodel=128 and 4 heads. Each head then uses 128÷4=32 features in the usual equal split. Concatenating four 32-feature results restores 4×32=128, so the residual shortcut can add the original 128-feature representation. The weights inside those projections are learned; the width and head count are architecture choices.

What Completes a Transformer Block?

Attention is one part of the block, not the whole block. The remaining parts transform the information, preserve a direct path through the network and keep feature values at a manageable scale.

Attention exchanges information

It lets token positions collect useful information from other allowed positions.

The feed-forward network transforms each position

After attention, the same small neural network is applied independently to each token representation.

A residual connection preserves a direct path

It adds the sublayer input back to its output, helping information and gradients travel through deep stacks. The two tensors must have matching dimensions.

LayerNorm stabilizes each token's features

It normalizes features within one token representation, then applies learned scale and shift parameters.

2D Transformer Block Architecture: Dual Residual Shortcuts & Normalization

True 2D computational topology showing parallel residual gradients bypassing attention and FFN sublayers.

Main Transformation TrunkResidual Shortcut (Add x)
Input Tokens x [B, L, d_model]Residual Bypass 1 (+x)Multi-Head Self-Attentionsoftmax(QK^T / √d_k) · V+LayerNorm (Stabilize)Residual Bypass 2 (+x)Feed-Forward Network (FFN)Linear(d → 4d) → GELU → Linear(4d → d)+LayerNorm → Block Output [B, L, d_model]
Each residual addition creates an unobstructed highway for error gradients (∂L/∂x = ∂L/∂sublayer + 1·∂L/∂x), solving the vanishing gradient problem in 100+ layer architectures.

The diagram shows a common post-norm ordering. In a pre-norm block, LayerNorm is applied before attention and before the feed-forward network. Both designs use the same main ingredients, but their exact ordering differs.

Position Information Restores Order

Self-attention alone compares token content without automatically knowing that one token is first and another is fifth. The model therefore adds a position vector to each token embedding. Positions may be fixed, learned or represented through relative/rotary methods in newer architectures.

The original sine–cosine encoding

PE(pos, 2i) = sin(pos / (100002i/dmodel))

PE(pos, 2i+1) = cos(pos / (100002i/dmodel))

pos is token position, i selects a sine/cosine frequency pair, and dmodel is the embedding width. For pos=1 and dmodel=4: the first pair is [sin(1), cos(1)]≈[0.841,0.540]; the second is [sin(0.01),cos(0.01)]≈[0.010,1.000]. Multiple frequencies give each position a distinctive smooth pattern.

Causal Masking Prevents the Decoder From Cheating

During training, the entire correct target sentence is available in the batch. We shift it right: <start>, “la”, “machine”… becomes the decoder input, while “la”, “machine”, “s’est”… is the prediction target. Without a mask, the representation at “la” could read the later correct word “machine.”

A causal mask blocks every future target token

Rows are queries; columns are keys. ✓ can be read and × is hidden.

key
<start>
key
the
key
motor
key
stopped
query <start>
✓
×
×
×
query the
✓
✓
×
×
query motor
✓
✓
✓
×
query stopped
✓
✓
✓
✓
When learning to predict the token after “the,” the representation for “the” may use <start> and itself, but it must not read “motor” or “stopped.” Otherwise training leaks the answers.

Padding mask and causal mask solve different problems

A padding mask hides artificial pad tokens used to make batch lengths equal. A causal mask hides real future tokens. An encoder often needs a padding mask but no causal mask; an autoregressive decoder generally needs both.

Training Is Parallel; Generation Is Autoregressive

Training with teacher forcing

  1. Feed all shifted correct target tokens.
  2. Apply the causal mask.
  3. Predict every next-token distribution together.
  4. Compute cross-entropy against the target IDs.

Autoregressive generation

  1. Begin with the start token or prompt.
  2. Predict a distribution for the next token.
  3. Select/sample one token and append it.
  4. Repeat until an end token or length limit.

The mismatch matters: training conditions on correct previous targets, while inference conditions on its own generated history. Search/decoding choices such as greedy decoding, beam search and sampling change outputs without retraining the model.

Choose the Transformer Family From the Output You Need

FamilyContext ruleOutputTypical use
Encoder-onlyAll input tokens attend bidirectionallyOne representation per input token or pooled inputClassification, extraction, embeddings
Decoder-onlyCausal self-attention over earlier tokensNext-token distribution at each positionAutoregressive text/code generation
Encoder–decoderEncoder reads source; decoder uses causal and cross-attentionA target sequence conditioned on sourceTranslation, summarization, structured transformation

These families are architectural patterns, not guarantees. A pretrained model matched to the language, domain, context length, licence, accuracy needs and hardware is usually a better starting point than training a Transformer from scratch.

Code the Masks Deliberately

PyTorch's reference Transformer expects embedded source and target tensors. The code below shows the important shape and mask relationship; a complete production system also needs tokenization, position encoding, an output vocabulary layer and a training loop.

transformer_shapes_and_masks.py
import torch
from torch import nn

batch, source_len, target_len, width = 8, 12, 9, 128
source = torch.randn(batch, source_len, width)
target_shifted = torch.randn(batch, target_len, width)

model = nn.Transformer(
    d_model=width,
    nhead=4,
    num_encoder_layers=3,
    num_decoder_layers=3,
    batch_first=True,
)

# 0 where attention is allowed; -inf above the diagonal.
causal_mask = nn.Transformer.generate_square_subsequent_mask(target_len)

# True means “ignore this padded key” for nn.Transformer masks.
source_is_pad = torch.zeros(batch, source_len, dtype=torch.bool)
target_is_pad = torch.zeros(batch, target_len, dtype=torch.bool)

decoder_states = model(
    src=source,
    tgt=target_shifted,
    tgt_mask=causal_mask,
    src_key_padding_mask=source_is_pad,
    tgt_key_padding_mask=target_is_pad,
    memory_key_padding_mask=source_is_pad,
)
print(decoder_states.shape)  # [8, 9, 128]

What the four dimensions mean

8 is a chosen batch size, 12 and 9 are example source and target lengths, and 128 is a chosen model width. Four heads imply 32 features per head. Three encoder and decoder layers are architecture choices, not values learned from the batch.

What the calls create

randn makes placeholder embedded inputs for shape testing. The mask helper writes 0 on allowed positions and −∞ on future positions; after softmax, e−∞=0 gives blocked tokens zero attention. The final tensor keeps one 128-feature decoder state for each of 9 target positions in each of 8 examples.

Mask conventions differ across APIs: in this module's boolean key-padding masks, True means blocked. Read the exact function documentation instead of reusing a mask by shape alone.

Common Transformer Failure Modes

SymptomLikely causeWhat to inspect
Training loss is unrealistically tinyDecoder can see future target tokensVisualize the causal mask and run a token-leakage test
Output changes when extra padding is addedPad tokens are not maskedCheck padding IDs, mask polarity and source/target/memory masks
Word order has little effectPosition information missing or misalignedTrace token IDs, positions and embeddings after truncation
Loss becomes NaNLarge logits, rate instability or all-masked attention rowInspect activations/gradients and ensure each query has an allowed key
Generation repeats foreverNo end-token handling or poor decoding settingsConfirm EOS ID, stopping criteria, repetition behavior and training targets
Out of memory on long documentsStandard attention score matrix is quadraticChunk/retrieve, reduce length/batch, or evaluate sparse/linear/SSM alternatives
Fine-tuning forgets useful behaviorRate too high or too little representative dataUse smaller rates, held-out evaluation and parameter-efficient strategies

Limits to Keep in View

Self-attention gives direct routes between positions, but standard global attention uses an N×N score matrix and can become expensive for long sequences. Transformers also require substantial data/compute when trained from scratch, can learn spurious correlations, and may generate fluent but unsupported content. Attention weights are not a guarantee of faithful reasoning.

Good systems therefore combine architecture with trustworthy data, task-appropriate metrics, leakage checks, robustness tests, latency/memory measurement and human review where errors carry real consequences.

The Transformer in Seven Sentences

  1. Learned projections turn each token representation into queries, keys and values.
  2. Self-attention lets positions in one sequence exchange weighted value information.
  3. Multiple heads repeat that operation in several learned representation spaces.
  4. Position information restores order that content-only attention does not supply.
  5. Residual shortcuts, normalization and position-wise feed-forward networks complete each block.
  6. Causal and padding masks prevent future-token leakage and hide artificial padding.
  7. Encoder-only, decoder-only and encoder–decoder families suit different outputs and require task-specific validation.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Transformers for Deep Learning"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • Transformers use attention for direct token-to-token information exchange.
  • Queries ask, keys describe, and values carry combined information.
  • Scaled scores and softmax produce attention weights.
  • Multiple heads learn varied interactions; feed-forward layers transform each position.
  • Residual paths and LayerNorm stabilize deep blocks.
  • Positions and masks define order and allowed interactions.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
In self-attention, what is the role of a query?
Question 2 of 5interpretation
Why divide dot-product attention scores by sqrt(d_k)?
Question 3 of 5conceptual
What does multi-head attention provide?
Question 4 of 5interpretation
Why must a residual sublayer output match its input dimension?
Question 5 of 5practical selection
What does a causal mask prevent?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1In self-attention, what is the role of a query?▼

Correct Answer: Represent what the current position is looking for

The query is compared with keys to determine which values should influence the position.

2Why divide dot-product attention scores by sqrt(d_k)?▼

Correct Answer: To keep score magnitudes from making softmax overly sharp

Dot products grow with key dimension; scaling keeps softmax and gradients in a useful range.

3What does multi-head attention provide?▼

Correct Answer: Several learned interaction subspaces

Different heads can focus on different relationships before their outputs are combined.

4Why must a residual sublayer output match its input dimension?▼

Correct Answer: The two tensors are added element-wise

A residual connection adds the original representation back to the sublayer output.

5What does a causal mask prevent?▼

Correct Answer: A token attending to future tokens

Autoregressive prediction may use only earlier and current tokens, not unseen future targets.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next