Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college extension →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

AttentionUnderstand the moving parts.

What Q, K, V actually are. Why scaled dot-product, why softmax, why heads.

Suggested preparation: 05

WORKBENCH / CHANGE ONE THING

Follow the weighted message

Change query strength and calculate a four-token attention distribution.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

Use four weighted votes to build one answer, then connect votes to similarity.

Where this deserves more time

Matrix shapes, stable softmax, masking, Jacobian and head concatenation.

Open the complete high-school reading

Moment 01 / 13

Course Introduction and Overview

Welcome to the course on attention mechanisms in modern AI architectures. We begin with the question driving the field: why did one differentiable weighting operation, popularized by Vaswani and colleagues in 2017, displace recurrence and convolution across sequence modeling.

Attention computes a content-dependent weighted sum over representations instead of compressing a sequence into one fixed vector. Removing that information bottleneck broke the limits of recurrent encoders and now underpins language, vision, and multimodal systems.

Our agenda runs from the scaled dot-product formulation, queries, keys, and values, through multi-head attention and causal masking, to the full Transformer block: residual streams, layer normalization, and positional encoding. We close with efficient variants and the scaling laws governing large models.

By the end you will derive attention gradients, reason about its quadratic cost in sequence length, and implement the mechanism from scratch rather than treating it as a black box.

Let us start with the core operation: match each query against every key, normalize with softmax, and read out a weighted combination of values.

Equations, code and original cards

Attention Mechanisms: Course Introduction and Overview

• Why attention displaced recurrence and convolution

• From scaled dot-product attention to the Transformer block

• Efficient attention, scaling laws, and current frontiers

Attention replaces the fixed-vector bottleneck of recurrent encoders with a content-addressable weighted sum, creating direct gradient paths between arbitrary positions in a sequence.

We derive scaled dot-product and multi-head attention, then assemble the Transformer block: causal masking, residual streams, layer normalization, and positional encoding.

Objectives: derive the gradients, quantify the quadratic cost in sequence length, analyze ablations from the literature, and implement the mechanism from scratch.

Moment 02 / 13

Conceptual Foundation: Queries, Keys, and Values

Today we dissect the attention mechanism's core projection: Queries, Keys, and Values. These three linear maps of the residual stream are what let transformers route information between positions, the central idea of Vaswani et al. 2017.

Each token's hidden state is projected three ways. The Query encodes what this position is looking for; the Key encodes what a position advertises about itself; the Value carries the actual content that gets forwarded if a match occurs.

Think of it as content-based retrieval rather than fixed convolution. The Query is a search request, Keys are index entries scattered across the context, and Values are the payloads those entries point to. Unlike a convolutional kernel, the routing pattern is computed per input, not learned once.

Concretely, attention scores are dot products between the Query and each Key, scaled by the square root of d-k, then softmaxed into a convex combination over Values. This is a differentiable soft lookup, and that differentiability is what makes the whole stack trainable end to end.

In summary, the query-key-value factorization decouples where to look from what to read. That inductive bias, content-addressable memory with quadratic attention cost in sequence length, underpins everything from machine translation to vision transformers.

Equations, code and original cards

Conceptual Foundation: Queries, Keys, and Values

Content-Addressable Retrieval in Attention (Vaswani et al. 2017)

• Queries (Q): Learned projection of the residual stream encoding what a position seeks

• Keys (K): Projection advertising what each position offers for matching

• Values (V): Projection carrying the content forwarded to the output

• Analogy: differentiable content-based retrieval

• Query: a search request issued by the current token

• Keys: index entries across the context

• Values: payloads retrieved on a match

• Mechanism:

• Scores: Q K-transpose dot products, scaled by square root of d-k

• Softmax yields a convex weighting over Values

• Soft lookup keeps the pipeline differentiable end to end

Moment 03 / 13

Interactive Exploration: Attention Heatmap

Let's probe the attention mechanism directly by visualizing the softmax weight matrix for different input sentences.

Notice how switching heads or query tokens reshapes the distribution, exposing the underlying query-key dot products, scaled by the square root of d-k, after softmax normalization.

Zoom in to inspect fine-grained alignment patterns, and reset the view anytime to start fresh.

Equations, code and original cards

Moment 04 / 13

Mathematical Formulation of Scaled Dot-Product Attention

This scene presents the mathematical formulation of scaled dot-product attention, the core operation of the transformer introduced by Vaswani and colleagues in 2017. We will walk through each step of the computation precisely.

Here is the core formula: attention of Q, K, V equals the softmax of Q times K transpose, divided by the square root of d-k, then multiplied by V. This single expression defines the entire scaled dot-product attention operation.

The matrices Q, K, and V — Query, Key, and Value — are learned linear projections of the input embeddings. Each row is a d-dimensional vector, and the product Q K transpose yields pairwise similarity scores between every query and key.

Dividing by the square root of d-k is essential: for random vectors, the variance of each dot product grows linearly with d-k. Without scaling, large logits push softmax into saturation, where gradients vanish and training stalls.

The softmax normalizes each row of scaled scores into a probability distribution over keys. Multiplying by V then produces a convex combination of value vectors, so each output position aggregates information in proportion to its attention weights.

Together these steps let the model route information content-addressably, at a cost of order n squared times d per layer. Stacked with residual connections, this mechanism underpins every modern transformer.

Equations, code and original cards

Mathematical Formulation of Scaled Dot-Product Attention (Vaswani et al., 2017)

\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\left( \frac{QK^{T}}{\sqrt{d_{k}}} \right)V

• Q, K, V: learned linear projections of the input embeddings

• \(QK^T\): pairwise query–key similarity logits

• Score shape: \(n_{query} \times n_{key}\); cost \(O(n^2 d_k)\)

• Scale by \(1/\sqrt{d_k}\): dot-product variance grows with \(d_k\)

• Unscaled logits saturate softmax in high dimensions

• Saturation causes vanishing gradients; scaling prevents it

• Softmax normalizes each row into a distribution over keys

• Output: convex combination of value vectors, weights times \(V\)

• Content-addressable routing of information across positions

Moment 05 / 13

Softmax Role and Properties in Attention

Softmax is the mechanism that turns attention logits into a usable distribution over keys. In the Vaswani transformer those logits are query-key dot products scaled by the square root of d-k, and the normalization choice is not cosmetic.

The map exponentiates each scaled logit and divides by the partition function over all keys, so every attention weight is positive and the row sums to one. The output is a point on the probability simplex, and each context vector is a convex combination of value vectors.

That simplex constraint is why the model can allocate probability mass proportionally instead of committing to a single key. The naive reading is that softmax picks the best match; it actually computes a differentiable relaxation of argmax whose entropy is controlled by temperature and logit scale.

Differentiability is the second key property. Softmax is smooth, its Jacobian couples every key in the row, and backpropagation can move probability mass between competing keys rather than stopping at a discrete winner.

With cross-entropy or KL divergence to a target distribution, the gradient is prediction minus target, which is clean and stable. But when logits grow too large, softmax saturates, attention entropy collapses, and gradient norms shrink; the root d-k scaling and temperature exist to keep logits in a useful regime.

So softmax balances three requirements: probabilistic interpretability, smooth optimization, and controllable sharpness. Change the temperature or the logit scale and you change the effective receptive field of attention.

Equations, code and original cards

Softmax in Attention: Simplex, Jacobian, Temperature

Probability Simplex

• Row-wise softmax over scaled query-key logits

• Weights positive; each row sums to one

Smooth Jacobian, End-to-End Learning

• Context is a convex combination of value vectors

• Gradients redistribute mass across all keys

Saturation, Entropy, Gradient Flow

• Large logits: low entropy, vanishing gradients

• Root d-k scaling and temperature set sharpness

\text{Softmax}(z_i) = \frac{e^{z_i}}{\sum_{j} e^{z_j}}

• softmax(z)_i = exp(z_i / T) / sum_j exp(z_j / T): normalized logits on the simplex

• Cross-entropy with one-hot targets reduces to negative log likelihood; KL compares full distributions

• Jacobian couples keys; sharper peaks increase confidence but can collapse entropy and slow learning

Moment 06 / 13

Multi-Head Attention: Motivation and Mechanics

Multi-head attention, introduced by Vaswani and colleagues in the twenty seventeen transformer paper, is the core routing operation: it lets the residual stream mix information across positions with learned, content-dependent weights.

The naive view is that heads mainly buy parallelism; the deeper point is that several small softmax attention maps run at once, each with lower-dimensional projections and independent inductive bias.

Because each head has its own query, key, and value projections, it can learn a distinct similarity geometry: syntax in one head, coreference in another, positional locality in a third.

For each head, project the residual stream into queries, keys, and values, compute softmax of queries times keys transpose over the square root of the head dimension, weight the values, concatenate heads, then apply the output projection.

A useful correction: heads are not independent models; they share the same tokens and residual stream, differ only through projection matrices, and are regularized by the final linear map that forces their features to compose.

So the gain is not magic width; it is structured factorization: many low-rank content-addressable channels, computed at roughly the cost of one full attention, then fused back into the residual stream for the next block.

Equations, code and original cards

Multi-Head Attention: Subspace Factorization and Mechanics

• Parallel low-rank attention maps, not extra depth

• Head-specific query, key, value projections define subspaces

• Concatenate heads, then output projection mixes evidence

Each head applies scaled dot-product attention to the same residual stream after learned projections into a lower-dimensional subspace; causal masking, when present, still restricts each position to its past.

The head outputs are concatenated and passed through one linear output projection, so diverse similarity geometries are fused before layer normalization and the feed-forward network.

\text{Multi-Head}(Q,K,V) = \text{Concat}(head_1, \ldots, head_h)W^O
\text{where } head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)

Moment 07 / 13

Gradient Derivations and Backpropagation Through Attention

Today we derive the gradients that flow through the attention block during backpropagation, the mechanism by which transformers actually learn. We focus on the partial derivatives of the loss with respect to the query, key, and value projections.

The chain rule decomposes these derivatives through each stage: the attention weights, the softmax normalization, and the scaled dot-product scores. Each factor contributes a Jacobian term to the total gradient.

The partial derivative of the loss with respect to Q passes through the softmax Jacobian, which is dense: every score couples to every other score through the normalization. The one over square root of d-k factor then rescales this gradient.

The efficient backward pass expresses these gradients as batched matrix multiplications rather than elementwise loops, so backward cost matches forward cost at order n-squared times d. Kernels like FlashAttention fuse both passes to avoid materializing the score matrix.

Tracing these flows shows the residual stream and value projections receiving additive gradient contributions, while the softmax Jacobian shrinks gradients when attention saturates, a stability concern the scaling factor mitigates.

In summary: the chain rule structures the derivation, the softmax Jacobian couples all scores, and the one over square root of d-k scaling controls gradient magnitude. Efficient kernels exploit matrix structure to keep backpropagation tractable. These principles underlie every transformer training run, from small ablations to models at the ten to the twenty-three FLOP scale.

Equations, code and original cards

Backpropagation Through Attention: Gradient Derivations

• Chain rule decomposes ∂L/∂Q, ∂L/∂K, ∂L/∂V through weights, softmax, and scores

• Softmax Jacobian diag(p) − ppᵀ is dense: every score couples to every other

• The 1/√d_k factor controls gradient magnitude and prevents saturation

\nabla_Q = \frac{\partial L}{\partial \mathrm{Attention}} \cdot \frac{\partial \mathrm{Attention}}{\partial Q},\quad \nabla_K = \frac{\partial L}{\partial \mathrm{Attention}} \cdot \frac{\partial \mathrm{Attention}}{\partial K},\quad \nabla_V = \frac{\partial L}{\partial \mathrm{Attention}} \cdot \frac{\partial \mathrm{Attention}}{\partial V}

• Backward pass as batched matmuls: cost matches forward O(n²d); FlashAttention fuses both

• Gradient analysis informs stability: saturation, initialization, and layer normalization

Moment 08 / 13

Implementation Details: Python and PyTorch Code

Let's examine the implementation of scaled dot-product attention in PyTorch. The core operation is Q K transpose scaled by the square root of d-k, followed by softmax and a weighted sum over values.

The key insight: batched matrix multiplication replaces iterative loops entirely. PyTorch's matmul broadcasts across batch and head dimensions, so a single call computes attention for all sequences simultaneously—this is what makes transformer training tractable on GPUs.

This snippet shows the full function. Queries, keys, and values enter as tensors; we compute raw scores, apply causal or padding masks by setting positions to negative infinity before softmax, then normalize and weight the values.

Masking is essential for correctness. Padding tokens must receive zero attention weight, and in autoregressive decoding, causal masking prevents position t from attending to future positions—preserving the factorization of the likelihood.

PyTorch's autograd tracks these operations for backpropagation, and fused kernels like FlashAttention further reduce memory by avoiding materialization of the full attention matrix.

To summarize: efficient attention relies on batched tensor ops and careful masking. Next, we extend this to multi-head attention, where parallel heads learn distinct representation subspaces.

Equations, code and original cards

Implementation Details: Python and PyTorch Code

• Batched matmul: Q K transpose over sqrt of d-k, then softmax

• Masking: negative infinity before softmax zeroes padded or future positions

• Autograd and fused kernels enable efficient backpropagation

# Scaled Dot-Product Attention (Vaswani et al. 2017)def scaled_dot_product_attention(q, k, v, mask=None):

Moment 09 / 13

Advanced Techniques and Optimizations (2024-2026)

We survey optimizations from 2024 to 2026: IO-aware exact attention, multi-query and grouped-query variants, rotary positional encodings, and the scaling laws governing compute-optimal training.

Sparse and approximate attention attack the order n-squared d cost by restricting each query to a subset of keys, trading exact softmax normalization for subquadratic compute.

Add zero for allowed pairs and negative infinity for excluded pairs before softmax. A causal mask alone still has quadratically many allowed pairs.

Zeroing it prunes low-relevance key value pairs, cutting FLOPs and memory traffic; the risk is a narrowed effective receptive field and occasional recall failures.

Scaling laws fit loss as a power law in parameters and data; Kaplan and Chinchilla imply roughly twenty tokens per parameter at the compute optimum.

The through-line is a Pareto frontier: memory bandwidth against FLOPs, exactness against sparsity, and alignment tax against capability, each ablated before deployment.

Clarification: Multiplying logits by a zero mask does not exclude them.

Equations, code and original cards

Advanced Attention: Systems, Sparsity, and Scaling (2024-2026)

• IO-aware exact attention and key value cache compression

• Sparse and approximate attention: subquadratic cost, recall risk

• Scaling and alignment: Chinchilla-optimal data, RLHF and DPO trade-offs

A=\operatorname{softmax}(QK^\top/\sqrt{d_k}+M)V;\quad M_{ij}\in\{0,-\infty\}
\text{Scaling Laws: } L(m) = a m^{-\alpha} + b

• Mask \(\mathbf{M}\) added to logits; softmax over allowed edges only

• Approximation trades exactness for memory bandwidth and FLOPs

• Kaplan and Hoffmann: loss power law in \(N,D\); compute-optimal \(N \approx 20D\)

Moment 10 / 13

Hands-on: Implement Your Own Attention Module

Open the code editor; you will implement scaled dot-product attention from Vaswani et al. 2017, not call a library.

Construct the query, key, and value projections yourself, then compute raw scores as Q K transpose.

Scale by the square root of d-k to keep pre-softmax variance stable, and sweep the softmax temperature to sharpen or flatten the distribution.

Inspect the attention weights and the output; track how temperature shifts entropy and how the output norm responds.

Equations, code and original cards

Moment 11 / 13

Cutting-Edge Variations and Open Research Questions

Let's examine the frontier of attention research: adaptive architectures, interpretability, and the open problems that will define the next generation of sequence models.

First, dynamic and adaptive attention. Rather than fixed heads, mechanisms like mixture-of-experts routing and adaptive computation time reallocate capacity per input, cutting FLOPs while preserving representational power.

Next, interpretability and alignment. Jain and Wallace showed in 2019 that attention weights are not faithful explanations, so probing what heads actually encode, and aligning behavior with human intent, remains open.

Finally, open problems: robustness under adversarial perturbation and distribution shift, length extrapolation beyond the training context, fairness, and scaling past the quadratic attention cost all demand new theory.

Together, these questions mark the frontier of attention research. Progress will require both sharper theory, from kernel approximations to scaling laws, and engineering advances like FlashAttention to push sequence models further.

Equations, code and original cards

Cutting-Edge Variations and Open Research Questions

Dynamic and Adaptive Attention Mechanisms

• Mixture-of-experts routing and adaptive computation time per input

• Head pruning: most heads removable at inference with minimal loss (Voita et al. 2019)

Interpretability and Alignment Challenges

• Attention weights are not faithful explanations (Jain & Wallace 2019)

• Mechanistic interpretability: circuits, induction heads, superposition

Open Problems & Research Opportunities

• Robustness to adversarial inputs and out-of-distribution shift

• Length extrapolation, multimodal fusion, and human-feedback alignment

Moment 12 / 13

Challenging Quiz: Conceptual & Computational

Time to test your command of attention: query-key compatibility, softmax normalization, causal masking, and the quadratic cost. Work through each question independently and precisely.

Once you submit, we'll walk through the solutions and correct any misconceptions about the mechanism.

Equations, code and original cards

Moment 13 / 13

Summary and Key Takeaways

Begin with the primitives: queries, keys, and values, and the scaled dot-product that turns them into attention weights. Each output is a convex combination of value vectors, weighted by the softmax of query-key dot products scaled by one over the square root of d-k; that scaling keeps logit variance stable as dimension grows.

Multi-head attention runs h such projections in parallel, letting the model attend jointly to different representation subspaces at different positions. Because a single softmax must average its weight somewhere, one head alone cannot capture competing relations; multiple heads resolve this at modest extra cost.

On the research frontier: efficient attention such as FlashAttention, which computes exact attention in tiles to avoid materializing the n-by-n matrix, and grouped-query attention, which shares keys and values across heads to shrink the inference cache. Interpretability and length generalization remain open.

The takeaways: attention is differentiable content-based retrieval, multi-head structure supplies representational diversity, and the field is actively optimizing both compute and memory. These mechanisms are the foundation on which every modern transformer is built.

Equations, code and original cards

Summary and Key Takeaways

• Q, K, V: content-based retrieval from the residual stream

• Scaled dot-product: softmax of QK^T / sqrt(d_k) stabilizes logit variance

• Multi-Head Attention: parallel subspaces, diverse relations

• Advances: FlashAttention, GQA/MQA, efficient inference

• Open: interpretability, length generalization, sub-quadratic attention

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

2 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.