Jump to content

Self-attention causal mask (Transformer)

From Wikibase

Languages: English · français · Esperanto

The self-attention causal mask forbids position $j$ from attending to any position after $j$ in an autoregressive decoder-only Transformer.

Standard scaled dot-product attention score

$$ \mathbf{S} = \frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}} \qquad\text{(raw scores, shape } T\times T\text{)} $$

where $T$ is the token sequence length.

The causal mask is a matrix $\mathbf{M} \in \mathbb{R}^{T\times T}$ defined as

$$ \mathbf{M}_{ij} = \begin{cases} 0, & j \le i \quad\text{(past and present are allowed)}\\[4pt] -\infty, & j > i \quad\text{(future is forbidden)} \end{cases} $$

The masked attention is then

$$ \operatorname{Attn}_{\text{causal}}(\mathbf{Q},\mathbf{K},\mathbf{V}) = \operatorname{softmax}\!\bigl(\mathbf{S} + \mathbf{M}\bigr)\,\mathbf{V} . $$

Example