Your Institute @yourname Sep 21, 2026 · 15:32

Attention Mechanism: Pseudocode

Demo note. This note demonstrates what the SciDraft Hugo theme can do for academic and scientific publishing — for research institutions, researchers and students. Its content is demonstration material only: readers should ignore whether the demo content is correct.

Attention lets a model decide, for each position it is processing, which other positions to draw information from. This note states the scaled dot-product form as an algorithm rather than as an equation, so the sequence of operations — and the shape of each intermediate result — is explicit.

The scaling by \( \sqrt{d_k} \) matters: without it, the dot products grow with the key dimension, the softmax saturates, and the weights collapse onto a single position.

Reading the algorithm. Steps 1–2 build the score matrix, where row \(i\) holds the compatibility of query \(i\) with every key; step 3 turns each row into a probability distribution, so a high score for one key means its value dominates that output row; step 4 mixes the values accordingly. Every row of the output therefore draws on a different combination of the same value matrix, which is what makes attention content-adaptive rather than fixed — at a cost of \(O(nm)\) for forming \(S\), the pressure behind the approximate and sparse variants.