Jump to content

Self-attention: Difference between revisions

From Wikibase
Definition, scaled dot-product form, causal masking, and complexity of self-attention — AI-assisted (RonzzWikiCowriter) (via create-page on MediaWiki MCP Server)
 
 
(12 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Category:Artificial neural network]]
[[Category:Transformer]]
[[Category:Large language models]]
'''Self-attention''' is the process through which a [[Transformer]] enriches its [[token embedding (machine learning)|token embedding vectors]] with contextual information derived from other tokens in the same token sequence.<ref>{{#cite:Q3130}}</ref>
'''Self-attention''' relates the positions of a sequence to one another, so that each position's representation is built from the whole sequence rather than from a fixed window.<ref>{{#cite:Q3130}}</ref>


== Definition ==
== Single-head attention ==


Let $\mathbf{X}\in\mathbb{R}^{T\times d}$ hold the representations of the $T$ positions in its rows, and let $\mathbf{W}_Q,\mathbf{W}_K,\mathbf{W}_V\in\mathbb{R}^{d\times d_k}$ be learned projections. The queries, keys, and values are
Let $\mathbf{X}\in\mathbb{R}^{T\times d}$ be the '''vector embedding matrix''' of [[token (machine learning)|token sequence]] $X$, in which row $t$ is the embedding vector for the token at position $t$.


$$
$$
Line 15: Line 14:
$$
$$


Each position scores itself against every other through a scaled dot product, and averages the values by the resulting weights,
where $\mathbf{W}_Q,\mathbf{W}_K,\mathbf{W}_V\in\mathbb{R}^{d\times d_k}$ are '''weight matrices''' learnt during training (e.g., via [[backpropagation]]).


Then the standard attention score
$$
$$
\operatorname{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V})
S_\text{attention}=\operatorname{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V})
=
=
\operatorname{softmax}\left(\frac{\mathbf{Q}\mathbf{K}^{\top}}{\sqrt{d_k}}\right)\mathbf{V},
\operatorname{row-wise\ softmax}\left(\frac{\mathbf{Q}\mathbf{K}^{\top}}{\sqrt{d_k}}\right)\mathbf{V},
$$
$$


where the [[Softmax|softmax]] is taken row-wise, and the factor $1/\sqrt{d_k}$ keeps the scores from growing with the dimension.
<blockquote>
The [[Softmax|softmax]] is taken row-wise so for each embedding vector $\vec x_t$ within $X$, $\sum_{i=1}^{d_k} (S_{\text{attention}})_{t,i} = 1$.


== Causal masking ==
The scaling factor $1/\sqrt{d_k}$ keeps the scores from growing with the dimension.


A decoder must not see later positions, so the scores above the diagonal are suppressed before the softmax,
Both are [[normalisation function]]s applied for numerical stability.
</blockquote>
 
<ref>{{#cite:Q3130}}</ref>
 
== Multi-head attention sub-layer and residual ==
 
In a standard [[Transformer]], each attention sub-layer has $h$ attention heads $\{\operatorname{head}_1(\mathbf{X}),\cdots,\operatorname{head}_h(\mathbf{X})\}$.
 
where for each $\operatorname{head}_i$


$$
$$
\mathbf{A}
S_\text{attention}(i)=\operatorname{Attention}(\mathbf{Q}_i,\mathbf{K}_i,\mathbf{V}_i).
$$
 
Define sub-layer '''residual'''
 
$$
\operatorname{SL}_{\text{attn}}(\mathbf{X})
=
=
\operatorname{softmax}\left(\frac{\mathbf{Q}\mathbf{K}^{\top}}{\sqrt{d_k}}+\mathbf{M}\right),
\left[S_\text{attention}(1),\cdots,S_\text{attention}(h)\right]\mathbf{W}_O
\qquad
\in\mathbb{R}^{T\times d},
M_{jk}=
\begin{cases}
0, & j\ge k, \\
-\infty, & j<k,
\end{cases}
$$
$$
where $\mathbf{W}_O\in\mathbb{R}^{hd_k\times d}$ is a '''weight matrix''' learnt during training.


so that position $j$ attends only to positions $k\le j$. This mask is what makes the output of position $j$ predictable from $x_{1:j}$ alone, and hence what allows a sequence to be generated one token at a time.
<blockquote>
The sublayer '''residual''' is then fed through [[residual connection (Transformer)|a residual connection mechanism]].
</blockquote>


== Complexity ==
== Complexity ==


The score matrix $\mathbf{Q}\mathbf{K}^{\top}$ is $T\times T$, so attention over a context of length $T$ costs $\mathcal{O}(T^2d)$ time and $\mathcal{O}(T^2)$ memory. Generating a sequence recomputes most of this work unless the keys and values already computed are kept, which is the purpose of [[KV caching]].
The complexity of standard multi-head self-attention
 
* Time $\propto O(T^2 d h)$
* Memory $\propto O(T^2 h)$
 
where $O$ is the [[o(x) and o(x)|big-O notation]].
 
{{Hidden proof}}
'''Compute time''':
 
'''Single attention head'''
 
Since
 
$$
\mathbf{Q}\in\mathbb{R}^{T\times d},\,
\mathbf{K}\in\mathbb{R}^{T\times d}
$$
 
so
 
$$
\mathbf{Q}\mathbf{K}^{\top}\in\mathbb{R}^{T\times T}.
$$
 
Computing one entry of $\mathbf{Q}\mathbf{K}^{\top}$ is a dot product of length $d$:
 
$$
(\mathbf{Q}\mathbf{K}^{\top})_{ij}
= \sum_{r=1}^{d} Q_{ir}K_{jr}.
$$
 
There are $T \times T = T^2$ such entries, and each costs $O(d)$ work. Therefore:
 
$$
\text{Time} \propto O(T^2 \cdot d).
$$
 
to calculate the score matrix.
 
After that, attention also computes
 
$$
\mathrm{softmax}(\mathbf{Q}\mathbf{K}^{\top})\mathbf{V},
$$
 
where $\mathbf{V}\in\mathbb{R}^{T\times d}$. The softmax touches the $T\times T$ score matrix, costing $O(T^2)$
 
Then, multiplying the $T\times T$ attention matrix by $\mathbf{V}$ costs another $O(T^2 d)$. So the attention cost per attention head is
 
$$
\text{Time} \propto O(T^2 d)+O(T^2)+O(T^2 d)=O(T^2 d).
$$
 
'''Multi-head aggregation and calculating residual'''
 
There are $h$ attention heads, for a total of $O(T^2 dh)$.
 
Note in addition to compute '''residual''' there is a $(T \times T)\times (T \times d)$, representing $Td$ dot $T$ dimensional [[vector dot product]]s, for a total of $O(T^2 d)$.
 
Hence the overall sub-layer compute is
 
$$
O(T^2 dh)+O(T^2 d)=O(T^2 dh).
$$
 
'''Memory''':
 
Since in a standard [[Transformer]] $T \gg d_k,d,h$, memory cost is dominated by the storage of $h$ $T \times T$ attention score matrices $S_\text{attention}(i)$, for a total of $O(T^2h)$.
{{End hidden}}
 
Generating a sequence of tokens in [[large language model (LLM)#Inference|inference]] recomputes most of this work unless the keys and values computed and cached, such as via [[KV caching]].
 
<ref>{{#cite:Q3130}}</ref>

Latest revision as of 11:28, 12 November 2026

Languages: English · français · Esperanto

Self-attention is the process through which a Transformer enriches its token embedding vectors with contextual information derived from other tokens in the same token sequence.[1]

Single-head attention

Let $\mathbf{X}\in\mathbb{R}^{T\times d}$ be the vector embedding matrix of token sequence $X$, in which row $t$ is the embedding vector for the token at position $t$.

$$ \mathbf{Q}=\mathbf{X}\mathbf{W}_Q, \qquad \mathbf{K}=\mathbf{X}\mathbf{W}_K, \qquad \mathbf{V}=\mathbf{X}\mathbf{W}_V. $$

where $\mathbf{W}_Q,\mathbf{W}_K,\mathbf{W}_V\in\mathbb{R}^{d\times d_k}$ are weight matrices learnt during training (e.g., via backpropagation).

Then the standard attention score $$ S_\text{attention}=\operatorname{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V}) = \operatorname{row-wise\ softmax}\left(\frac{\mathbf{Q}\mathbf{K}^{\top}}{\sqrt{d_k}}\right)\mathbf{V}, $$

The softmax is taken row-wise so for each embedding vector $\vec x_t$ within $X$, $\sum_{i=1}^{d_k} (S_{\text{attention}})_{t,i} = 1$.

The scaling factor $1/\sqrt{d_k}$ keeps the scores from growing with the dimension.

Both are normalisation functions applied for numerical stability.

[1]

Multi-head attention sub-layer and residual

In a standard Transformer, each attention sub-layer has $h$ attention heads $\{\operatorname{head}_1(\mathbf{X}),\cdots,\operatorname{head}_h(\mathbf{X})\}$.

where for each $\operatorname{head}_i$

$$ S_\text{attention}(i)=\operatorname{Attention}(\mathbf{Q}_i,\mathbf{K}_i,\mathbf{V}_i). $$

Define sub-layer residual

$$ \operatorname{SL}_{\text{attn}}(\mathbf{X}) = \left[S_\text{attention}(1),\cdots,S_\text{attention}(h)\right]\mathbf{W}_O \in\mathbb{R}^{T\times d}, $$ where $\mathbf{W}_O\in\mathbb{R}^{hd_k\times d}$ is a weight matrix learnt during training.

The sublayer residual is then fed through a residual connection mechanism.

Complexity

The complexity of standard multi-head self-attention

  • Time $\propto O(T^2 d h)$
  • Memory $\propto O(T^2 h)$

where $O$ is the big-O notation.

Generating a sequence of tokens in inference recomputes most of this work unless the keys and values computed and cached, such as via KV caching.

[1]