Position Problem › Attention Is Permutation Equivariant

Michael BrenndoerferUpdated June 5, 202510 min read
Language AI HandbookAll chapters
Part 14 of 67Positional Encoding
Chapter 96Position Problem › Attention Is Permutation Equivariant
Reading section 2 of 11 · Attention Is Permutation Equivariant · 10 minSection 2 of 11 · 10 min

Book contents

Section 2 of 11 · 10 min read

Position Problem › Attention Is Permutation EquivariantOne section · Sections in this chapter2 / 11 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

To understand why self-attention ignores position, we need to examine its mathematical structure with care. The conclusion that self-attention is position-blind is not intuitive at first, because the computation does produce one output vector per position. It looks like position is being tracked. But appearances are deceiving. Let's build up the key insight step by step, starting with precise definitions and culminating in a demonstration that reveals where position information is missing.

Permutation Invariance vs. Equivariance

Two related properties appear throughout machine learning, and distinguishing them clarifies exactly what kind of symmetry self-attention has.

A function is permutation invariant if reordering its inputs leaves the output completely unchanged. Computing the mean of a set of numbers is permutation invariant: the mean of {3,7,2,5}\{3, 7, 2, 5\} is the same as the mean of {5,2,7,3}\{5, 2, 7, 3\}. Set membership and operations such as summation or taking a maximum have the same property. Permutation invariant functions discard order entirely.

A function is permutation equivariant if reordering the inputs causes the outputs to be reordered in exactly the same way. If you feed a permuted input, you get back the same outputs you would have gotten from the original input, just rearranged by the same permutation. Formally, a function ff is permutation equivariant if for any permutation π\pi:

f(π(X))=π(f(X))f(\pi(\mathbf{X})) = \pi(f(\mathbf{X}))

where:

  • X\mathbf{X}: the input sequence (a matrix where each row is a token's embedding)
  • π\pi: any permutation of the row indices
  • f(X)f(\mathbf{X}): the output sequence produced by the function ff
  • π(f(X))\pi(f(\mathbf{X})): that same output, with its rows rearranged by π\pi

Self-attention falls squarely into the equivariant category, not the invariant category.

Permutation Equivariance

A function ff is permutation equivariant if for any permutation π\pi applied to the input sequence, the output is permuted in the same way: f(π(X))=π(f(X))f(\pi(\mathbf{X})) = \pi(f(\mathbf{X})). Self-attention has this property because it processes all positions using the same computation with no position-specific parameters or inputs. Every position is treated identically by the machinery of attention.

Why does equivariance matter more than invariance here? Invariance would be even more extreme: the output itself would not change when we reorder inputs. Self-attention at least tracks which output corresponds to which input, which is why we describe it as equivariant rather than invariant. But equivariance is still problematic for language, because it means the model cannot tell from the outputs alone whether the input was "dog bites man" or "man bites dog." The relative ordering between positions carries no information. Two sequences that are permutations of each other produce outputs that are the same permutation of each other.

The key insight is this: permutation equivariance means that reordering the input has exactly the same effect as reordering the output. The attention mechanism does not encode any relationship between input positions that survives reordering. It is as if the attention computation is computed in a "coordinate-free" space where positions have no identity.

Tracing the Mathematics

To see why permutation equivariance emerges, we need to trace through the self-attention computation and identify every place where position could enter, but does not.

Self-attention produces an output vector for each position by aggregating information from all positions. For position ii, we compute a weighted sum where each position jj contributes its value vector, scaled by how relevant it is to position ii. This is the fundamental operation of attention:

yi=∑j=1nαijvj\mathbf{y}_i = \sum_{j=1}^{n} \alpha_{ij} \mathbf{v}_j

where:

  • yi∈Rdv\mathbf{y}_i \in \mathbb{R}^{d_v}: the output representation for position ii
  • αij\alpha_{ij}: the attention weight from position ii to position jj (determines how much jj contributes to ii's output)
  • vj∈Rdv\mathbf{v}_j \in \mathbb{R}^{d_v}: the value vector at position jj (the information that position jj contributes)
  • nn: the sequence length
  • ∑j=1n\sum_{j=1}^{n}: summation over all positions in the sequence

Notice that the formula is a weighted sum: a linear combination of value vectors. The weight αij\alpha_{ij} controls how much of position jj's value flows into position ii's output. If αij\alpha_{ij} is large, position jj has a strong influence on position ii's representation. If αij\alpha_{ij} is near zero, position jj contributes almost nothing.

This formula shows that the output at position ii depends on all value vectors vj\mathbf{v}_j and all attention weights αij\alpha_{ij}. But notice: the values come from the token content, and the weights come from content comparisons. Where does position enter?

The attention weights themselves come from applying softmax to scaled dot products between query and key vectors. The softmax function converts raw similarity scores into a probability distribution. This keeps all weights are positive and sum to 1:

αij=exp⁡ ⁣(qi⋅kj/dk)∑l=1nexp⁡ ⁣(qi⋅kl/dk)\alpha_{ij} = \frac{\exp\!\left(\mathbf{q}_i \cdot \mathbf{k}_j / \sqrt{d_k}\right)}{\sum_{l=1}^{n} \exp\!\left(\mathbf{q}_i \cdot \mathbf{k}_l / \sqrt{d_k}\right)}

where:

  • αij\alpha_{ij}: the attention weight from position ii to position jj (how much position ii attends to position jj)
  • qi∈Rdk\mathbf{q}_i \in \mathbb{R}^{d_k}: the query vector for position ii
  • kj∈Rdk\mathbf{k}_j \in \mathbb{R}^{d_k}: the key vector for position jj
  • dkd_k: the dimension of query and key vectors (used for scaling)
  • exp⁡(⋅)\exp(\cdot): the exponential function. This keeps all values are positive
  • ∑l=1n\sum_{l=1}^{n}: summation over all nn positions, serving as the normalizing constant

The queries and keys are computed by multiplying the input embedding by learned weight matrices. For position ii with input embedding xi\mathbf{x}_i:

qi=xiWQ,ki=xiWK,vi=xiWV\mathbf{q}_i = \mathbf{x}_i \mathbf{W}_Q, \quad \mathbf{k}_i = \mathbf{x}_i \mathbf{W}_K, \quad \mathbf{v}_i = \mathbf{x}_i \mathbf{W}_V

where WQ\mathbf{W}_Q, WK\mathbf{W}_K, and WV\mathbf{W}_V are the learned projection matrices shared across all positions. The same matrices are applied to every token, regardless of where it appears in the sequence.

The Missing Position Signal

Here is the critical observation: examine both equations carefully and notice what is absent. The indices ii and jj appear only as subscripts identifying which vectors to retrieve. They never appear as values in the computation itself. The attention weight αij\alpha_{ij} depends entirely on:

  1. The query vector qi\mathbf{q}_i, which is derived from the content at position ii (the token embedding xi\mathbf{x}_i)
  2. The key vector kj\mathbf{k}_j, which is derived from the content at position jj (the token embedding xj\mathbf{x}_j)
  3. The normalization over all keys, which also depends only on content

Position indices serve as labels that tell us which output corresponds to which input. They are bookkeeping, not input features. The number ii or jj itself never enters any arithmetic operation. If we swap the tokens at positions 2 and 5, the query and key vectors simply swap, and the computation produces swapped outputs. The absolute values 2 and 5 played no role.

Think of it as the difference between a library catalog (where shelf number matters for retrieval) and a set of books on a table (where the arrangement of books has no permanent identity). Self-attention is the table: books can be rearranged and the pairwise relationships remain identical, just reordered.

This contrasts sharply with recurrent networks. In an RNN or LSTM, position is implicitly encoded through sequential processing. The hidden state at step 5 depends on the hidden state at step 4, which depends on step 3, and so on. The temporal chain of computation bakes position into the representation as an inductive bias: earlier tokens shape later representations in ways that later tokens cannot shape earlier ones. Self-attention discards this sequential chain entirely, processing all positions in parallel and achieving massive efficiency gains, but at the cost of positional awareness.

Demonstrating Permutation Equivariance

The mathematical argument is clear, but seeing the effect in code makes it concrete. Let's implement self-attention and verify that permuting the input produces identically permuted output.

In[3]:
Code
import numpy as np

np.random.seed(42)


def softmax(x, axis=-1):
    """Compute softmax along the specified axis."""
    exp_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
    return exp_x / np.sum(exp_x, axis=axis, keepdims=True)


def self_attention(X, W_Q, W_K, W_V):
    """
    Compute self-attention output.

    Args:
        X: Input embeddings of shape (seq_len, embed_dim)
        W_Q, W_K, W_V: Projection matrices

    Returns:
        Output representations of shape (seq_len, d_v)
    """
    Q = X @ W_Q
    K = X @ W_K
    V = X @ W_V

    d_k = K.shape[1]
    scores = Q @ K.T / np.sqrt(d_k)
    weights = softmax(scores, axis=-1)
    output = weights @ V

    return output, weights

We will create a simple 4-token sequence, apply a permutation that swaps two positions, and compare the outputs.

In[4]:
Code
# Create embeddings for a 4-token sequence
seq_len = 4
embed_dim = 8
d_k = d_v = 6

# Random embeddings representing different tokens
X = np.random.randn(seq_len, embed_dim)

# Initialize projection matrices
W_Q = np.random.randn(embed_dim, d_k) * 0.1
W_K = np.random.randn(embed_dim, d_k) * 0.1
W_V = np.random.randn(embed_dim, d_v) * 0.1

# Compute attention on original sequence
output_original, weights_original = self_attention(X, W_Q, W_K, W_V)

# Create a permutation: swap positions 1 and 2
permutation = [0, 2, 1, 3]
X_permuted = X[permutation]

# Compute attention on permuted sequence
output_permuted, weights_permuted = self_attention(X_permuted, W_Q, W_K, W_V)

# Apply the same permutation to the original output for comparison
output_original_reordered = output_original[permutation]
Out[5]:
Console
Permutation applied: [0, 2, 1, 3] (swap positions 1 and 2)

Original output shape: (4, 6)
Permuted output shape: (4, 6)

Max difference between pi(output) and output(pi(input)): 2.78e-17
Outputs are identical (within numerical precision)

The outputs match exactly, up to floating-point precision. This confirms permutation equivariance: permuting the input permutes the output in the same way. Self-attention does not "know" that we reordered the tokens. It computes the same pairwise relationships in a different order and produces the same outputs in a different order. No information about the original positions has been preserved beyond the assignment of outputs to input slots.

The Root Cause: Content-Only Dependencies

This experiment confirms what the mathematics predicted. Self-attention treats the input as an unordered set of tokens, using only their content to determine relationships. Each token's output depends on three things, none of which involve position:

  1. Its own content (through its query vector, which asks "what am I looking for?")
  2. The content of all other tokens (through their key vectors, which answer "what do I offer?")
  3. The pairwise content relationships (through dot products that measure semantic compatibility)

This is a deliberate architectural choice, not an oversight. The original Transformer designers wanted to avoid the sequential bottleneck of RNNs, where position is encoded implicitly by the order of computation. Parallelizing across all positions means forgoing positional inductive bias. The model is given maximum flexibility to learn relationships from content alone, but that flexibility comes with the responsibility of explicitly injecting position information from outside the attention mechanism.

Notice that this is quite different from convolutional neural networks (CNNs), which have a different kind of positional inductive bias. A CNN's filters are applied at specific spatial locations, and nearby positions share features through local connectivity. Position is implicitly encoded through the spatial structure of the convolution. Self-attention has no analogous spatial structure. It is maximally flexible with respect to distance.