Macalinao StudioLearn
Course library ↗

Attention learning module

Learn Transformers / Attention

Follow the
thought.

From a word in a sentence to a new representation.
One complete journey. Three ways to understand it.

12 moments · 4 experiment milestones · 6 mastery checks
About 25–35 minutes with experiments · self-paced
Many paths, one evolving representationitCONTEXT BECOMES MEANINGCompare → normalize → combine
ONE IDEA, MADE VISIBLE

Watch it. Change it. Explain it.

Go a little deeper
Field Notes / The context issue

No word
is an island.

The whole lesson, at your own reading pace. Every section connects back to its diagram and narration.

01 / Find the context

A small word.
A whole world of context.

You naturally connect “it” with “animal”. A transformer must work with numbers. Attention lets one position gather a weighted mixture of information from other available positions. A strong connection means a larger contribution to that mixture—not a human thought or a guaranteed explanation.

Throughout this module, we follow four content tokens: animal, street, it, and tired. The omitted words keep the arithmetic small. In a real sequence, every available token participates, and positional information helps distinguish order.

By the end, you should be able to compute one attention row, explain what Q, K and V do, apply a causal mask, combine heads, and recognize the main computational cost. Basic vector multiplication is useful; the first pass builds intuition before the details.

Mathematical detail

Self-attention transforms an n × d_model sequence representation into another sequence representation. Every query has its own distribution over keys. It does not reduce the entire sequence to a single vector.

Words are shown as tokens for clarity. Real tokenizers can split words into smaller pieces. Our four-token numerical example is deliberately hand-built; it is not a trained model or proof of how a language model resolves this sentence.

02 / Queries, keys, values

One representation.
Three different jobs.

Each token begins with a vector in X. Three learned linear transformations create queries, keys and values: Q = XW_Q, K = XW_K, and V = XW_V. They share an input, but they do different jobs.

Queries and keys are compared to decide the weights. Values supply the content. Changing only V changes the resulting mixture without changing the weights. Changing Q or K can change which positions contribute most.

Select a token in the stage. The matrix multiplication is shown explicitly for that token. In this example X has four rows and two columns; each projection is a two-by-two matrix. Real models use much larger vectors and often many heads.

Mathematical detail

Q has shape n_q × d_k; K is n_k × d_k; V is n_k × d_v. Queries and keys need matching feature dimensions for their dot product. Values need one row per key, but d_v need not equal d_k. In cross-attention, Q can come from a different sequence than K and V.

Projection matrices are learned during training. Our small matrices are chosen for legibility, and have no trained semantic interpretation.

03 / Compare & scale

A connection starts
as a number.

For the query at “it”, compare q with every key k_j. The dot product q · k_j adds the coordinate-wise products. Positive, larger scores indicate stronger compatibility in this learned space; negative scores are allowed.

The standard scaled score is s_j = (q · k_j) / √d_k. In our example d_k = 2. Scaling helps keep the variance of scores manageable as the key dimension grows. It reduces the tendency for large logits to push softmax into very sharp, weak-gradient regions.

Enter the Workbench and move the query coordinates. Watch the scores change before normalization. A zero query gives equal scores to all keys. A query pointing toward the second coordinate favors the street key in our chosen example.

Mathematical detail

If independent q_i and k_i have mean zero and variance one, Var(Σ q_i k_i) = d_k. Dividing by √d_k gives variance one under those assumptions. Scaling q before the dot product or scaling the product afterward is mathematically equivalent; finite-precision implementations can differ.

A dot product is a learned compatibility score. It is not generally cosine similarity: vector magnitudes also affect it.

04 / Normalize the scores

Turn scores
into a distribution.

Softmax exponentiates the scaled scores and divides each exponential by the sum over allowed keys. For one query, the result is a distribution. It expresses relative emphasis: a score matters in relation to its competitors.

For numerical stability, subtract the largest allowed score before exponentiating. This changes neither the distribution nor the ranking, because the same common factor cancels in the numerator and denominator.

Temperature is an extra teaching control. At a lower positive temperature, the distribution becomes more concentrated. At a higher temperature, it becomes more even. Equal scores produce equal weights at any positive temperature.

Mathematical detail

p_j = exp((s_j − m)/τ) / Σ_l exp((s_l − m)/τ), where m is the maximum allowed score. Normalization runs across keys for each query—not down the query column. With masks, forbidden entries are excluded from both the maximum and denominator.

The temperature slider is a teaching control applied to attention logits. Standard scaled dot-product attention uses τ = 1; this is distinct from temperature used when sampling next-token predictions.

05 / Mix the values

The answer is
a new vector.

Attention does not normally choose one value and discard the rest. It computes a weighted sum: z = Σ_j p_j v_j. The same scalar weight multiplies every coordinate in a value vector. Then corresponding coordinates are added.

The stage breaks the output into its contributions. Notice that the weights come from Q and K, but the coordinates being mixed come from V. If you doubled every value coordinate, the output would double while the attention weights stayed the same.

Before dropout or later projections, nonnegative weights summing to one make the result a convex combination of the allowed value vectors. Multiple heads can provide different mixtures, and the following projection can combine their coordinates.

Mathematical detail

For a batch of queries, Z = PV, with P shaped n_q × n_k and V shaped n_k × d_v. The result is n_q × d_v. Example: Q 2×3, K 4×3, V 4×5 → scores 2×4 → weights 2×4 → output 2×5.

This is one head’s output before output projection, residual addition, and later layers. Its two coordinates are arbitrary teaching features, not probabilities over words.

06 / Respect the boundary

Some connections
must stay closed.

During autoregressive language modeling, position i must not obtain information from later positions. A causal mask allows keys at positions j ≤ i and excludes keys with j > i. Training usually shifts the prediction target so the current position predicts the next token.

Conceptually, add negative infinity to the forbidden logits before softmax. Their weights become zero. The remaining allowed entries still sum to one. Setting forbidden scores to zero is not equivalent: exp(0) is one, so the forbidden entries could retain weight.

In the Workbench, turn on the mask and choose “it”. The connection to “tired” closes. Then select the first token: only its own key is available, so its weight becomes one. Encoder self-attention often uses a different, noncausal visibility pattern.

Mathematical detail

Scores S are n × n. A causal mask M has M_ij = 0 for j ≤ i and −∞ otherwise. P = softmax(S + M). Every row must retain at least one allowed key; softmax of an all-masked row is undefined without a specified fallback.

The four selected tokens retain their order in the sentence. With query “it”, “tired” is later and is masked. This is a simplified subsequence, not a full tokenizer output.

07 / Look in parallel

One question.
More than one perspective.

A single set of Q, K and V projections defines one head. Multi-head attention uses several sets in parallel. Each head can compare and mix information in a different subspace of the representation.

The head outputs are concatenated along the feature dimension. A learned output matrix W_O combines those features. Concatenation is not generally averaging; our small output projection happens to average corresponding coordinates so the result is easy to inspect.

Compare both heads in the Workbench. Head A favors the first feature for the default query; Head B swaps the query’s emphasis. Their distributions differ even though they read the same four input vectors.

Mathematical detail

head_h = softmax(Q_h K_hᵀ / √d_k + M)V_h. MultiHead(X) = Concat(head_1,…,head_H)W_O. Two 2D head outputs concatenate to four coordinates. Here W_O is 4×2 with 0.5 on paired coordinates; in a trained model it is learned.

Head A and Head B are deliberately hand-built. Real heads are learned, need not have tidy human-readable jobs, and do not always specialize in a single linguistic relationship.

08 / Place it in the model

Attention is a layer.
Learning is the system.

Attention is one component of a transformer. A residual path adds the attention result back to the running representation. A feed-forward network transforms each position’s features, and a second residual connection preserves another direct path.

Layer normalization helps control the scale of activations. In a common pre-normalization block, normalization occurs before attention and before the feed-forward network. Other designs arrange it differently.

Attention alone does not know the order of a set of vectors. Positional information is therefore introduced through the representations or the attention computation. Absolute encodings and relative or rotary approaches are different ways to provide order.

Mathematical detail

A pre-norm example is H = X + MultiHead(LN(X)); Y = H + FFN(LN(H)). Without positional signals, ordinary unmasked self-attention is permutation equivariant. Causal masking supplies an order-dependent visibility structure but does not replace all positional design choices.

The diagram shows a common pre-normalization block. The original Transformer paper used post-normalization; architectures vary.

09 / How it learns

Every weight
affects the others.

Training adjusts the projection matrices using gradients of a loss. The value path is direct: if a value receives a larger weight, it contributes more strongly to the output and to that path’s gradient.

The softmax couples its inputs. Increasing one logit raises its own probability and reduces other probabilities. Its Jacobian is diag(p) − ppᵀ. The diagonal entries are nonnegative and the off-diagonal entries are nonpositive.

When a distribution is extremely concentrated, many entries of this Jacobian become small. That explains the concern about saturation. Scaling, initialization, normalization, and numerical precision all influence training behavior; scaling alone does not guarantee stable training.

Mathematical detail

Let G = ∂L/∂Z. Then ∂L/∂V = PᵀG and ∂L/∂P = GVᵀ. For a row with upstream gradient g, ∂L/∂s = p ⊙ (g − (p·g)1) at τ=1. With S=QKᵀ/√d_k: ∂L/∂Q=(∂L/∂S)K/√d_k and ∂L/∂K=(∂L/∂S)ᵀQ/√d_k. Masked logits have no gradient through the excluded edges.

The displayed Jacobian is for softmax with respect to its input logits. Gradients with respect to pre-temperature scaled scores include another factor of 1/τ.

10 / Understand the cost

Longer context.
A much larger conversation.

For n tokens, every query can compare with n keys. That produces n² pairs per head. The score and weighted-value multiplications have quadratic dependence on sequence length for dense attention, at fixed feature dimensions.

A naive implementation materializes the whole score or probability matrix. Memory-efficient exact attention can avoid keeping that entire intermediate in high-bandwidth memory. FlashAttention uses tiled computation and reduces memory traffic while computing exact attention up to numerical precision.

Sparse or approximate methods change which pairs are considered or how they are represented. They can reduce cost but introduce different trade-offs. Grouped-query attention shares key/value heads to reduce cache cost; a KV cache reuses prior keys and values during decoding. Neither makes all long-context costs disappear.

Mathematical detail

Dense attention’s score/value work is O(n²d) at fixed head configuration; projections add O(nd_model²). A naive score matrix has O(n²) storage. Exact memory-efficient kernels do not imply subquadratic arithmetic. Attention weights alone are also not a complete causal explanation of model behavior.

The memory estimate is only one dense n × n score matrix for one head at two bytes per entry. It excludes batches, other heads, activations, gradients, caches, and implementation overhead.

11 / Build the operation

Make the idea
executable.

Implementation makes hidden assumptions visible. First form QKᵀ, then scale by √d_k. Add the visibility mask before normalization. Apply a numerically stable softmax across keys for each query, and finally multiply the weights by V.

The Workbench implementation exercise asks you to choose the score operation, scaling, normalization direction, and final matrix. It evaluates actual results against reference fixtures, including equal logits, a causal first row, and a nontrivial two-feature example.

The Python reference mirrors this sequence with shape checks and explicit handling of all-masked rows. In a framework, use its tested attention operation when appropriate, and verify mask conventions, dropout settings and tensor layouts against that framework’s documentation.

Mathematical detail

A boolean mask can mean “allowed” or “blocked” depending on the API. Do not copy mask conventions blindly. For evaluation, verify dropout is disabled. Numerical equivalence tests should use tolerances, since fused kernels and different reduction orders can change floating-point rounding.

This exercise executes the selected matrix operations in the browser. The downloadable Python reference uses only the standard library. It does not load a model or send your work to a server.

12 / Make it yours

From a connection
to an understanding.

Try to explain the operation without looking: queries compare with keys; scaled and masked scores become normalized weights; those weights mix values. Multiple heads repeat the process with different projections and combine their outputs.

Then transfer the idea. What changes when you alter only values? Which positions can a causal first token see? What grows quadratically with context length? These questions reveal whether the pieces are connected.

After the checks, keep a short note in your own words. You can export your notes and experiment settings as a portable learning record. Continue into QKV projections or building attention into a transformer when you are ready.

Mathematical detail

A high attention weight is neither a guarantee of linguistic importance nor a complete causal account of a prediction. Representations, values, other heads, residual paths and later layers all influence the final model behavior.

There is no time limit. Review an explanation, revisit a lab, and try again. A completed module means all six checks and four experiment milestones are correct; it is a practice milestone, not a formal qualification.

LISTEN & FOLLOW

Narration

Kokoro Heart · local narration
Press play when you’re ready.
Make a connection of your own

Your field note.

Explain attention to tomorrow’s you. Your note stays in this browser.

Continue with context
Next: QKV projections ↗Build attention into a model ↗Download runnable Python reference ↓Original enriched attention lesson ↗
Sources & scope

This module adapts the existing OpenMAIC attention lesson. Examples are illustrative, with explicit matrices and verified calculations.

Narration is generated locally with Kokoro Heart; audio is served from this site. No audio plays automatically. The four-token example is not a trained model. Progress is local to this browser and can be exported.

ATTENTION / ILLUSTRATIVE MODEL

Start this module again?

This clears your progress, lab milestones, answers and field note for this module on this browser. Export your learning record first if you want to keep it.