core34 min studyLesson 17 in Engineering

Attention and the Transformer computation

Compute a small attention example, understand causal masks, and separate architecture from capability claims.

On this page

What you’ll understand

  • Explain the roles of queries, keys, and values.
  • Compute masked softmax attention by hand.
  • Recognize causal leakage and sequence-length costs.

Attention lets one position combine information from other positions using weights computed from the current representations. A Transformer builds larger networks around this operation, with feed-forward transformations, residual paths, normalization, and information about order. Rather than treating attention as a metaphor for human thought, inspect the arithmetic: which positions can communicate, what weights they receive, and what information those weights mix.

Queries choose a weighted mixture of values

Each input representation is projected into a query, a key, and a value. A query compares with keys to produce scores; softmax turns an allowed row of scores into nonnegative weights summing to one; those weights mix the values. A key is therefore used for matching, while a value carries the content being combined. They can be learned from the same input without being the same vector. Multiple heads perform different learned projections and their outputs are combined.

Dividing dot-product scores by the square root of key dimension controls their scale under a rough independent-component variance argument. It is not a probability-calibration theorem. Position information is needed because content-only attention does not by itself encode a sequence's order. Different architectures represent positions differently; the original Transformer used sinusoidal encodings. Attention weights describe one internal mixing operation, but should not automatically be interpreted as a faithful explanation of the model's final decision.

Attention⁡(Q,K,V)=softmax⁡ ⁣(QKTdk+M)V\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\!\left(\frac{QK^\mathsf T}{\sqrt{d_k}}+M\right)V
Softmax is row-wise. Q and K share key dimension d_k; V may have another feature dimension. M is an additive mask with zero on allowed pairs and negative infinity on excluded pairs.↔ Scroll wide equations horizontally.

A mask is an information boundary

An autoregressive model predicting the next token must not read future target tokens. A causal mask allows a position to read its own representation and earlier positions but excludes later ones. During teacher-forced training, the real prefix is available and the target is shifted to the following token. A wrongly shifted target or incorrectly oriented triangular mask can make loss look impressive by allowing the answer to enter its own prediction. Verify a tiny sequence where every allowed dependency is visible.

Padding masks serve a separate purpose: padding is not real context and should not contribute as a key. Ensure every computed attention row has an intended valid source; a softmax over only negative infinities is undefined in ordinary arithmetic. Library mask conventions are not universal. For example, a boolean mask's meaning can differ between attention interfaces, so check the exact API rather than copying a tensor from another function. Test mask behavior through changed inputs, not shape checks alone.

Mij={0j≤i−∞j>i,p(x1:T)=∏t=1Tp(xt∣x<t)M_{ij}=\begin{cases}0&j\le i\\-\infty&j>i\end{cases},\qquad p(x_{1:T})=\prod_{t=1}^{T}p(x_t\mid x_{<t})
This causal mask is for self-attention ordered left to right. The factorization is a probability chain rule; in training, input and target shifts must implement the corresponding prefix condition.↔ Scroll wide equations horizontally.

Architecture creates useful work and real costs

Dense attention computes a score for every allowed query-key pair, giving quadratic pairwise work in sequence length for the standard dense formulation. Doubling context can therefore be much more expensive than doubling a batch dimension. Memory-efficient implementations can avoid storing the entire score matrix without changing the intended exact attention result up to floating-point differences; that does not erase all pairwise arithmetic. Other attention patterns trade different communication structures and approximation assumptions against cost.

An attention layer alone is not a language model. Tokenization, embeddings, normalization placement, residual connections, feed-forward layers, the training objective, and data all influence behavior. During generation, cached keys and values avoid recomputing some prefix work but consume memory that grows with context. Investigate a model with small controlled examples: changing a masked future token should not alter an earlier position's causal prediction. An architectural diagram becomes useful when it suggests a falsifiable behavior check.

Mask first, then normalize

One query has already-scaled scores 0, ln(3), and ln(9), with scalar values 2, 6, and 100. The third position is forbidden by the causal mask.

  1. Replace the third score by negative infinity before softmax. Its exponential contribution becomes zero even though its original score was largest.

  2. The remaining unnormalized weights are 1 and 3, whose sum is 4. Normalized weights are 1/4, 3/4, and 0.

  3. Mix the values: (1/4)×2+(3/4)×6+0×100=5. If the forbidden value changes, this output stays 5, which is a useful mask regression check.

The result

The allowed attention mixture is 5. Zeroing the third weight after a three-way softmax without renormalizing would produce the wrong mixture.

Explore the model

Interactive lab

Interactive lab · network

Inspect one nonlinear computation

The lab exposes a single sigmoid of wx−0.5 with input and weight controls. Use it to inspect how learned weights transform signals; it does not compute softmax attention, causal masks, multiple heads, or a full Transformer.

Inspect one nonlinear computationOne inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Current readings: Product · wx: 1.2; Logit · wx − 0.5: 0.7; Sigmoid output: 0.6682. All parameters are adjustable with the labeled controls below.One input. One weight. One sigmoid.x1.20× w1.20+ b0.70σ0.668output0.668w = 1.00b = −0.50σ(z) = 1 / (1 + exp(−z))
Computation graphSignal trace
Product · wx
1.2
Logit · wx − 0.5
0.7
Sigmoid output
0.6682
t = 0 s

One inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forStart by auditing elementary computations, then audit the information paths of the larger architecture separately.

Check your understanding

In a correctly masked causal model, changing only a future token should do what to an earlier position's output?

Try it yourself

Two allowed values are 4 and 10 with equal attention scores. Find the output. Then exclude the second value with a mask and recompute.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Softmax assigns equal weights to equal allowed scores, but an excluded score contributes zero mass before normalization.

Compare with the solution

Initially the weights are one-half and one-half, giving 7. After excluding the second source, the sole allowed source has weight one, giving 4. The operation is a mixture of allowed values, not a sum divided by the original sequence length.

Take it with you

  • Queries and keys determine weights; values are what those weights mix.
  • Causal masks must block every path to future targets.
  • Context length, attention implementation, and cache memory require explicit accounting.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.