Self-attention is equivariant with respect to input permutations, which is why we need positional encodings.

Why is it bad for self-attention (w/o positional encoding) to be equivariant with respect to input permutations?

No notion of token order. "The woman ate the raccoon" and "the raccoon ate the woman" produce the same attention matrix/output but permuted.

Absolute positional encodings

A matrix is added to the input that encodes positional information. Assuming the input has shape , where each row corresponds to one input token, each row of is unique and hence contains information about the absolute position in the input sequence. This matrix can be chosen by hand or learned. It may be added to the network inputs or at every network layer. Sometimes it is added to in the computation of the queries and keys but not the values.

Positional Encoding-1782599885259.webp

Relative positional encodings

The input to a self-attention mechanism might be a fragment of a sentence, an entire sentence, or even many sentences. Thus, the absolute position of a word is less important than the relative position between two words. Of course, this can be recovered if the system knows the absolute position of both, but relative positional encodings encode this information directly.

Each element of the attention matrix corresponds to a particular offset between key position and query position . Relative positional encodings learn a parameter for each offset and use this to modify the attention matrix by adding these values, multiplying by them, or using them to alter the attention matrix in some way.