TensorTau PathToAGI Sequences Language and Transformers Level 09

Level 09 · Sequences Language and Transformers · Chapter 135

Attention: What Should I Look At

🧪 Interactive Lab

The matching notebook is the complete hands-on laboratory for this lesson. It contains the runnable code, experiments, visualizations, and challenges.

🧭 Where this lesson fits

Previous lesson: Blog 15 — How Can a Computer Represent the Meaning of a Word?.

Today: Blog 16 — Attention: What Should I Look At?.

Next lesson: Blog 17 — Transformers: Building With Attention.

Student rule: if you cannot explain why this lesson follows the previous one, stop and reread the final takeaway of the previous blog. The equations below should feel like a continuation, not a new language.

1. The central question

For a token, ask:

Which other tokens should influence my representation right now?

Attention turns that question into mathematics.


2. Queries, keys and values

For each token representation, a neural network produces three vectors:

  • Query (QQ): what am I looking for?
  • Key (KK): what information do I offer for matching?
  • Value (VV): what information should be passed along?

The projections are typically

Q=XWQ,K=XWK,V=XWVQ=XW_Q,\qquad K=XW_K,\qquad V=XW_V

where XX contains the input token representations.


3. Compare a query with keys

The simplest comparison is a dot product:

QKTQK^T

Each entry measures how strongly a query matches a key.

For example, if

Q=[12]Q=\begin{bmatrix}1&2\end{bmatrix}

and

K=[21]K=\begin{bmatrix}2&1\end{bmatrix}

then

QKT=1(2)+2(1)=4QK^T=1(2)+2(1)=4

A larger score means a stronger raw match.


4. Why divide by dk\sqrt{d_k}?

Scaled dot-product attention uses

QKTdk\frac{QK^T}{\sqrt{d_k}}

where dkd_k is the key dimension.

The scaling helps keep dot-product magnitudes in a useful range as dimensionality grows, which helps the softmax behave better during optimization.


5. Softmax turns scores into weights

Suppose the scores are

[2,1,0][2,1,0]

Softmax is

softmax⁡(zi)=ezi∑jezj\operatorname{softmax}(z_i)= \frac{e^{z_i}}{\sum_j e^{z_j}}

The outputs are positive and sum to 1.

So attention scores become weights that describe how strongly to combine the values.


6. The complete formula

The standard scaled dot-product attention equation is

Attention⁡(Q,K,V)=softmax⁡(QKTdk)V\boxed{ \operatorname{Attention}(Q,K,V)= \operatorname{softmax} \left( \frac{QK^T}{\sqrt{d_k}} \right)V }

This looks intimidating, but read it left to right:

  1. compare queries with keys;
  2. scale the scores;
  3. turn scores into weights with softmax;
  4. use the weights to mix the values.

7. A visual mental model

flowchart LR
    X[Token representations] --> Q[Queries]
    X --> K[Keys]
    X --> V[Values]
    Q --> S[QK^T / sqrt(dk)]
    K --> S
    S --> P[Softmax weights]
    P --> O[Weighted values]
    V --> O

Attention is therefore a learned information-routing mechanism.


8. Self-attention

When the queries, keys and values all come from the same sequence, we call it self-attention.

Every token can compare itself with other tokens and build a new representation using information from the sequence.

This is a major reason Transformers can model long-range relationships effectively.


9. Causal attention

For language generation, a token should not normally look into the future.

For the sequence

I love deep learning

when predicting the next token, the model can use previous tokens but should not peek at future target tokens.

A causal mask enforces this restriction.

        I  love  deep  learning
I       ✓   ×     ×      ×
love    ✓   ✓     ×      ×
deep    ✓   ✓     ✓      ×

The exact mask convention depends on implementation, but the principle is future information is blocked.


10. PyTorch

Modern PyTorch provides attention-related building blocks. A conceptual example is:

import torch
import torch.nn.functional as F

Q = torch.randn(2, 4, 8)
K = torch.randn(2, 4, 8)
V = torch.randn(2, 4, 8)

scores = Q @ K.transpose(-2, -1)
scores = scores / (K.size(-1) ** 0.5)
weights = F.softmax(scores, dim=-1)
out = weights @ V

print(out.shape)

This code exposes the mathematics directly.


Think Like a Scientist 🧠

Suppose the query is the word “bank”.

Imagine the sentence:

“I deposited money at the bank.”

Which words should receive strong attention?

Now change it to:

“We sat beside the river bank.”

Which words should matter now?

The surrounding context changes the useful information.


What you should remember

Attention lets each representation selectively combine information from other representations.

The central equation is

softmax⁡(QKTdk)V\operatorname{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

This single idea became the foundation of the Transformer architecture.

Next: Transformers — building an entire architecture around attention.


📚 Go Deeper — The Core of Modern LLMs

3Blue1Brown is an excellent visual companion for understanding attention and Transformer ideas.

ZacharyLLM is especially relevant from this point forward because attention, token representations and Transformer internals are central to modern LLMs.

Frame Zero provides another first-principles route into modern ML concepts.

Visual Kernel is useful when you want additional visual/technical intuition about model internals.

Welch Labs provides a valuable hands-on philosophy: derive the mechanism, implement it, and inspect what the model is doing. Its AI resources explicitly combine detailed graphics with exercises and supporting code.

Use MrJensenMath10 to reinforce dot products, matrices, exponentials and probability—the exact mathematical ingredients appearing here.

The most important exercise

Do not memorize the attention equation.

Be able to reconstruct it:

match→scale→normalize→mix values\boxed{ \text{match} \rightarrow \text{scale} \rightarrow \text{normalize} \rightarrow \text{mix values} }

Once that sequence is intuitive, the Transformer becomes much easier to understand.

Six ways to work the chapter, climbing from explaining it in your own words to investigating it like a researcher. Reading is not enough — this is where the chapter lands.

Exercises should progress from understanding to research behaviour.

Level 1 — Explain it

Explain the idea in plain language without equations.

Level 2 — Calculate it

Solve a tiny numerical example by hand.

Level 3 — Predict it

Predict code output, model behaviour, tensor shapes, or graph movement before running anything.

Level 4 — Break it

Deliberately change an assumption or parameter and explain what fails.

Level 5 — Build it

Implement the core mechanism from scratch before using a high-level library.

Level 6 — Investigate it

Form a hypothesis, design an experiment, compare alternatives, and explain the evidence.