Everything on the site.

Big-O notationAlgorithms · Count the steps in real loops, then compare n, n log n, n² and 2ⁿ on a live chart.RecursionAlgorithms · Watch frames push and pop on the call stack for factorial and Fibonacci.BFS vs DFSAlgorithms · A queue against a stack: draw a graph and see which order each search visits it in.Sorting algorithmsAlgorithms · Seven sorts on the same input, with comparison, swap and write counts side by side.Binary searchAlgorithms · Halve the range, probe the middle, repeat: with lo, mid and hi drawn on the array.Sets, relations and functionsDiscrete maths · Shade any set expression on a Venn diagram and test a relation for its properties.Proof by inductionDiscrete maths · Four worked proofs revealed one step at a time, and a broken one to diagnose.CombinatoricsDiscrete maths · An exact nPr and nCr calculator, and a Pascal’s triangle that shows its own addition rule.Boolean algebraDiscrete maths · The laws, De Morgan, and normal forms, with a truth-table generator built in.Finite-state machinesTheory · Build a DFA in a table, see it drawn, and run strings through it one symbol at a time.Domain theoryTheory · Why recursion needs least fixed points, and how CPOs, Scott continuity and powerdomains supply them.Truth table generatorTools · Expression in, truth table out: with DNF, CNF, a minimal form and LaTeX.Graph traversal visualiserTools · Draw a graph, then animate BFS, DFS and Dijkstra with the frontier shown.Recursion tree visualiserTools · Paste a recursive function or a recurrence and see its call tree and call count.Gradient descentML maths · Drag the starting point, set the learning rate, and watch it converge or blow up.Vectors and embeddingsML maths · Bend the plane with a 2×2 matrix and measure how close toy word vectors are.Softmax and cross-entropyML maths · Edit the logits and watch the probabilities, the loss and the gradient update live.AttentionML maths · Q, K and V for three tokens, a live score heatmap, and the weighted sum of values.Formatting a CS paper in LaTeXLaTeX · Page limits, \documentclass, front matter, theorem environments and the bibliography.Camera-ready checklistLaTeX · Fonts embedded, PDF/A, copyright form, source bundle, and why final versions get rejected.LaTeX templatesLaTeX · Where the official classes live, plus a minimal article template you can copy.AlgorithmsSection · Step-through visualisations of sorting, searching, recursion, graph traversal and Big-O growth, each with pseudocode that highlights the line being run.Discrete mathsSection · Sets, relations and functions, proof by induction, counting, and Boolean algebra, explained with worked examples and small interactive checkers.TheorySection · Finite-state machines, automata and the mathematical semantics of programming languages, explained from first principles.ML mathsSection · Gradient descent, vectors and embeddings, softmax and cross-entropy, and attention, each with a formula, a worked numeric example and a live version.ToolsSection · A truth-table generator with CNF, DNF and LaTeX output, a graph-traversal visualiser for BFS, DFS and Dijkstra, and a recursion-tree visualiser.LaTeXSection · How to format a CS conference or workshop paper in LaTeX, a camera-ready checklist, and a minimal template you can adapt.
ML maths

Attention, worked through with three tokens

Attention lets each token in a sequence build its representation from the others, weighting each by how relevant it is. It is the core operation of the transformer. This page works through it with three tokens and two-dimensional vectors, small enough to check every number by hand.

Interactive: Three-token attention calculator with a score heatmapUpdated

The idea

In the sentence “the cat sat”, what “sat” means depends on who sat. Attention gives every token a way to look up information from the other tokens. Each token produces three vectors:

  • a query qq: what this token is looking for;
  • a key kk: what this token offers to be found by;
  • a value vv: the information it hands over when found.

A token compares its query with every key using a dot product, turns the scores into weights with softmax, and takes the weighted average of the values. It is a soft, differentiable version of a dictionary lookup: instead of returning the one value whose key matches, it returns a blend, weighted by how well each key matches.

The formula

Stack the token embeddings as the rows of a matrix XX. Three learned weight matrices produce the queries, keys and values for all tokens at once:

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

Then scaled dot-product attention is

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V,\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right) V,

where softmax is applied to each row separately and dkd_k is the length of the key vectors. Entry (i,j)(i, j) of QK⊤QK^\top is qi⋅kjq_i \cdot k_j, the score of token ii attending to token jj.

Why divide by dk\sqrt{d_k}?

If the entries of qq and kk are roughly independent with mean 0 and variance 1, their dot product has variance dkd_k. With dk=64d_k = 64, typical scores would be around ±8, and softmax of such spread-out numbers is almost one-hot: one weight near 1, the rest near 0, with gradients near zero. Dividing by dk\sqrt{d_k} brings the variance back to 1 and keeps the softmax in a range where it can learn.

Worked example

Step 1: queries, keys and values

The tokens “the”, “cat” and “sat” have embeddings (1,0)(1,0), (0,1)(0,1) and (1,1)(1,1). With the weight matrices

WQ=(1012),WK=(2001),WV=(1002)W_Q = \begin{pmatrix} 1 & 0 \\ 1 & 2 \end{pmatrix},\quad W_K = \begin{pmatrix} 2 & 0 \\ 0 & 1 \end{pmatrix},\quad W_V = \begin{pmatrix} 1 & 0 \\ 0 & 2 \end{pmatrix}

we get, multiplying row by row,

Q=(101222),K=(200121),V=(100212).Q = \begin{pmatrix} 1 & 0 \\ 1 & 2 \\ 2 & 2 \end{pmatrix},\quad K = \begin{pmatrix} 2 & 0 \\ 0 & 1 \\ 2 & 1 \end{pmatrix},\quad V = \begin{pmatrix} 1 & 0 \\ 0 & 2 \\ 1 & 2 \end{pmatrix}.

For example, the query for “sat” is (1,1) WQ=(1+1,  0+2)=(2,2)(1, 1)\,W_Q = (1 + 1,\; 0 + 2) = (2, 2).

Step 2: scores

Every query dotted with every key gives QK⊤QK^\top; then divide by dk=2≈1.414\sqrt{d_k} = \sqrt 2 \approx 1.414:

QK⊤=(202224426)⟶QK⊤2=(1.4140.0001.4141.4141.4142.8282.8281.4144.243).QK^{\top} = \begin{pmatrix} 2 & 0 & 2 \\ 2 & 2 & 4 \\ 4 & 2 & 6 \end{pmatrix} \quad\longrightarrow\quad \frac{QK^{\top}}{\sqrt 2} = \begin{pmatrix} 1.414 & 0.000 & 1.414 \\ 1.414 & 1.414 & 2.828 \\ 2.828 & 1.414 & 4.243 \end{pmatrix}.

Row 3 is “sat”: qsat⋅kthe=2⋅2+2⋅0=4q_{\text{sat}} \cdot k_{\text{the}} = 2 \cdot 2 + 2 \cdot 0 = 4, qsat⋅kcat=2q_{\text{sat}} \cdot k_{\text{cat}} = 2, qsat⋅ksat=6q_{\text{sat}} \cdot k_{\text{sat}} = 6.

Step 3: softmax each row

A=(0.4460.1080.4460.1640.1640.6730.1870.0450.768)A = \begin{pmatrix} 0.446 & 0.108 & 0.446 \\ 0.164 & 0.164 & 0.673 \\ 0.187 & 0.045 & 0.768 \end{pmatrix}

For “sat”: e2.828,e1.414,e4.243≈16.92,4.11,69.6e^{2.828}, e^{1.414}, e^{4.243} \approx 16.92, 4.11, 69.6, which sum to about 90.6, giving weights 0.187, 0.045, 0.768. “sat” attends mostly to itself and somewhat to “the”. Each row sums to 1.

Step 4: weighted sum of values

Z=AV=(0.8921.1080.8361.6730.9551.627)Z = AV = \begin{pmatrix} 0.892 & 1.108 \\ 0.836 & 1.673 \\ 0.955 & 1.627 \end{pmatrix}

For “sat”: 0.187 (1,0)+0.045 (0,2)+0.768 (1,2)≈(0.955,1.627)0.187\,(1, 0) + 0.045\,(0, 2) + 0.768\,(1, 2) \approx (0.955, 1.627). That vector, a blend of the three tokens’ values, is the new representation of “sat”.

Try it

The widget starts from the same numbers. Edit any embedding or weight and every matrix updates. Click a row of the heatmap to see that token’s calculation written out.

Scaled dot-product attention, three tokens

Token embeddings X (one row per token)
the
cat
sat
W_Q
W_K
W_V

Attention weights A = softmax(QKᵀ / √d) (click a row)

Causal masking

A model that generates text one token at a time must not let a token look at tokens that come after it, or training would let it cheat by reading the answer. The fix is a causal mask: before the softmax, set every score with j>ij > i to −∞-\infty, so its weight becomes exactly 0. In the example, “the” can then only attend to itself (weight 1), “cat” splits its attention between “the” and itself (0.500 and 0.500), and “sat” is unchanged because it was already last. Tick the checkbox in the widget to see it.

From one head to a transformer

  • Multi-head attention. Instead of one set of WQ,WK,WVW_Q, W_K, W_V, a layer runs several in parallel (often 8 to 128 heads), each with smaller vectors, and concatenates the results. Different heads can specialise: one may track which noun a pronoun refers to, another the previous token.
  • Position. Attention by itself ignores order: shuffle the tokens and the outputs shuffle the same way. Transformers add positional information to the embeddings, or build it into the scores, so that order can matter.
  • Cost. The score matrix has an entry for every pair of tokens, so attention over a sequence of length nn takes O(n2d)O(n^2 d) time and O(n2)O(n^2) memory. That quadratic cost is why long context windows are expensive, and the target of a great deal of research.
Where it came from Attention was introduced for machine translation in 2014, letting a decoder look back at the relevant words of the source sentence. The 2017 transformer paper, “Attention is all you need”, dropped recurrence entirely and built the whole model from attention and simple feed-forward layers.

References

  1. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser and I. Polosukhin, “Attention is all you need”, NeurIPS 2017. arXiv:1706.03762
  2. D. Bahdanau, K. Cho and Y. Bengio, “Neural machine translation by jointly learning to align and translate”, ICLR 2015. arXiv:1409.0473
  3. 3Blue1Brown, Neural networks, whose later chapters explain transformers and attention visually.