Jump to content

Self-attention: Difference between revisions

From Wikibase
Line 32: Line 32:


<ref>{{#cite:Q3130}}</ref>
<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$.
where for each head $\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[\operatorname{head}_1(\mathbf{X}),\cdots,\operatorname{head}_h(\mathbf{X})\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.


== Complexity ==
== Complexity ==

Revision as of 11:11, 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$.

where for each head $\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[\operatorname{head}_1(\mathbf{X}),\cdots,\operatorname{head}_h(\mathbf{X})\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.

Complexity

The complexity of standard self-attention

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

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]