🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Attention Mechanisms — Deep Dive

Deep LearningAttention🟢 Free Lesson

Deep Learning

Attention Is All You Need — The Mechanism Behind Modern AI

Master the attention mechanism that powers Transformers and enables state-of-the-art AI performance.

  • Self-attention — weigh importance of different input parts
  • Multi-head attention — capture different types of relationships
  • Scalability — process sequences of any length efficiently

Where attention goes, energy flows.

Attention Mechanisms — Deep Dive

Attention is a mechanism that allows models to dynamically focus on relevant parts of the input when producing each element of the output. It was originally proposed for seq2seq models (Bahdanau et al., 2014) and is now the foundation of all modern deep learning architectures.


Types of Attention

Attention Mechanism TypesSelf-Attentionh₁h₂h₃h₄Input attends to ITSELFEach token relates to ALL tokensUsed in: Encoder, decoderCaptures internal relationshipsCross-AttentionEncoder outk₁k₂k₃Decoder Qq₁q₂Output attends to INPUTDecoder Q queries encoder K,VUsed in: Encoder-DecoderLinks input and outputCausal (Masked) Attentiont₁t₂t₃t₄Each token attends to PREVIOUS onlyCannot look at future tokensUsed in: GPT, autoregressiveEnables text generationAttention ComparisonTypeMaskComplexityUse CaseSelf-AttentionNone (bidirectional)O(n²·d)BERT, encoderCausal Self-AttnLower triangularO(n²·d)GPT, decoderCross-AttentionNoneO(n·m·d)Seq2Seq, encoder-decoderSparse AttentionFixed patternO(n·√n·d)Long sequencesLinear AttentionNoneO(n·d²)Very long sequences

How this diagram works: This diagram compares the three main attention variants side by side. Self-attention (left) lets every token attend to every other token, capturing internal relationships — used in BERT and encoder layers. Cross-attention (middle) lets decoder queries attend to encoder keys and values, bridging input and output in seq2seq models. Causal attention (right) masks future tokens so each position only sees previous ones, enabling autoregressive generation in GPT. The comparison table below summarizes their masking patterns, computational complexity, and typical use cases.

Why the Mask Changes Everything

The only difference between the left box and the right box is a matrix of zeros and negative infinities added before the softmax, and that single change decides what the model is allowed to know. In a bidirectional encoder every position may read every other position, which is what makes BERT good at filling a blank in the middle of a sentence: the answer sits on both sides of the hole. In an autoregressive decoder position four must not read position five, or the model could copy the answer instead of predicting it, and training would quietly leak the labels.

Cross-attention keeps the mask open but changes where the keys and values come from. The query vector is produced by the decoder's current output position, while keys and values are read from the encoder output, so the model can align one word of the translation with a span of the source sentence. That alignment is the mechanism behind the attention heat maps popularised with the original sequence-to-sequence work.

python
import numpy as np

def softmax(x, axis=-1):
    e = np.exp(x - x.max(axis=axis, keepdims=True))
    return e / e.sum(axis=axis, keepdims=True)

def scaled_dot_product(Q, K, V, causal=False):
    scores = Q @ K.T / np.sqrt(Q.shape[-1])          # (n, n)
    if causal:
        n = scores.shape[0]
        allowed = np.tril(np.ones((n, n))) == 1
        scores = np.where(allowed, scores, -1e9)      # block the future
    return softmax(scores) @ V

rng = np.random.default_rng(0)
Q, K, V = (rng.normal(size=(4, 8)) for _ in range(3))

print(np.round(scaled_dot_product(Q, K, V), 3))
print(np.round(scaled_dot_product(Q, K, V, causal=True), 3))

Compare the two printed matrices: with the causal flag, every entry above the diagonal collapses to zero after the softmax, because those logits were set to a large negative number before normalisation. Each row still sums to one, so the operation remains a weighted average — it is simply restricted to history.


Multi-Head Attention

Multi-Head Attention: Why Multiple Heads?Input Xn×dmodelHead 1Subject-VerbAttn(Q1,K1,V1)Head 2Semantic RoleAttn(Q2,K2,V2)Head 3CoreferenceAttn(Q3,K3,V3)Head 4TemporalAttn(Q4,K4,V4)Concat(head₁,...headh)WOLinearOutputn×dmodelHead VisualizationsHead 1Head 2Head 3Head 4

What the Heads Actually Specialise In

Splitting a 512-dimensional representation into eight heads of 64 dimensions each costs almost nothing in parameters — four square matrices per layer regardless of head count — but it changes what the layer can represent. A single attention head produces one weighted average per position, so it can highlight one relationship at a time. Eight heads produce eight averages, which are concatenated and mixed by the output projection, allowing the same layer to track subject and verb agreement, coreference, nearby syntactic neighbours and a distant antecedent simultaneously rather than forcing one pattern to win.

Visualisation studies usually find that a handful of heads specialise sharply while others stay broad. One head frequently attends to the token immediately before or after each word, another to the same word in a previous clause, and another to the sentence boundary. Because the heads are learned rather than assigned, this structure is not guaranteed, and pruning or merging heads is a common compression trick: models usually tolerate losing many heads with little loss in accuracy.

python
import torch
import torch.nn as nn

layer = nn.MultiheadAttention(embed_dim=64, num_heads=8, batch_first=True)
x = torch.randn(2, 10, 64)                     # batch, sequence, d_model

out, weights = layer(x, x, x, need_weights=True)

print(out.shape)                               # torch.Size([2, 10, 64])
print(weights.shape)                           # torch.Size([2, 10, 10])
print(sum(p.numel() for p in layer.parameters()))   # 16640

The output keeps the original shape, so multi-head attention is a drop-in replacement for a single head inside a residual block. The weights returned for inspection are averaged across heads unless you ask for them individually, which is why visualisations look smoother than any single head really is.


Efficient Attention Mechanisms

Efficient Attention VariantsStandardO(n² · d)Full attention matrixn=4096 → 16M entriesMemory bottleneckSparse AttentionO(n · √n · d)Attend to k tokens onlyFixed/local patternsBigBird, LongformerLinear AttentionO(n · d²)Avoid n×n matrixkernel approximationPerformer, Linear Trans.Flash AttentionO(n² · d)Same complexitybut 2-4x fasterIO-aware, tilingFlash Attention (Dao et al., 2022)Key insight: Standard attention is memory-bandwidth bound, not compute-bound. The bottleneck is reading the n×n attention matrix from HBM.Flash Attention uses tiling: process attention in blocks that fit in SRAM. Avoids materializing the full n×n matrix. Same result, 2-4x faster, 5-20x less memory.Used in: GPT-4, LLaMA, Mistral, all modern LLMs. The single most important attention optimization.KV Cache (Autoregressive)During generation, K and V for previous tokens are cached.Only compute Q for the new token. Avoids recomputation.Cost: O(n·d) memory per layer for cacheGrouped Query Attention (GQA)Share K,V heads across multiple Q heads.Reduces KV cache size by factor of g (num groups).Used in: LLaMA-2 70B, Mistral, Gemma

The Memory Arithmetic

Working through the numbers explains why these variants exist. A sequence of 4,096 tokens produces a 4,096 by 4,096 matrix per head per layer: about sixteen million entries, and with sixteen heads across thirty-two layers the activations dominate the model's memory long before the weights do. Halving the context length cuts that cost by four, which is why context growth has historically been limited by memory rather than by compute.

Flash attention does not change the asymptotics at all — it still computes every pair — but it changes where the numbers live. The standard implementation writes the full matrix to high-bandwidth memory and reads it back for the softmax, while Flash attention works in tiles that fit in the small, fast on-chip memory and rescales partial results as it goes. Nothing is written to disk, the result is equivalent up to floating-point ordering, and the practical effect is several times the throughput at a fraction of the activation memory.

Sparse and linear attention take a different route and genuinely reduce the number of pairs evaluated. A local window plus a few global tokens covers most language workloads, since nearby words carry most of the attention mass in practice. The trade is that long-range links must be routed through the pattern instead of discovered freely, so accuracy on tasks that depend on distant context has to be measured before the swap.


Attention Computation


Common Mistakes & How to Avoid Them

Common Mistakes

Dropping the division by the square root of the key dimension, which pushes logits into a range where softmax saturates and gradients vanish

Fix: Scale scores by 1 over the square root of d_k before the softmax, and check that the attention weights are not collapsing onto a single position

Feeding a decoder a full bidirectional attention mask during training, then watching it cheat by copying the next token

Fix: Apply a lower-triangular mask in causal self-attention, and unit-test it by asserting that every weight above the diagonal is zero after softmax

Assuming the attention weights returned by a library are per-head maps

Fix: Request each head separately when inspecting behaviour, since the default is an average across heads and averaging hides the specialists you are looking for


Key Takeaways


What to Learn Next

-> Transformers Apply attention in complete architectures.

-> BERT See attention in bidirectional models.

-> GPT Architecture Explore autoregressive attention.

-> RNNs and LSTMs Compare with recurrent approaches.

-> Training Deep Networks Master optimizers and regularization.

-> CNNs Understand local vs global attention.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement