Linear Attention › The Linear Attention Formula
Language AI HandbookAll chapters Linear Attention › The Linear Attention FormulaOne section · Sections in this chapter3 / 15 ↓
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
Having established the mathematical foundation, we can now synthesize everything into the complete linear attention formula. The journey from standard attention to linear attention follows a clear logical path: we identified the softmax as the source of the quadratic bottleneck, replaced it with a decomposable kernel function, and discovered that the resulting expression can be rearranged to avoid computing the full attention matrix. Now let's see how these insights combine into a practical algorithm.
From Element-wise to Matrix Form
We derived earlier that each position's output can be written as:
To express this for all positions simultaneously, we stack the feature-mapped queries into a matrix and apply the same operations in parallel. For a sequence of tokens with queries , keys , and values , the complete formula is:
Let's unpack each component to understand how the pieces fit together:
-
: The feature map applied row-wise to the query matrix. Each of the query vectors is transformed from dimensions to dimensions.
-
: Similarly, the feature map applied to each key vector. After transformation, we transpose this to get .
-
: This is the key-value aggregate from our derivation. The matrix product has shape . Notice that disappears from the result shape, and this is precisely why linear attention avoids the quadratic bottleneck.
-
: Multiplying the queries by the aggregate produces the numerator. Shape: .
-
: Summing the transformed keys (equivalent to in our derivation). The vector of ones sums across all key positions, producing a -dimensional vector.
-
The division is performed element-wise per row, normalizing each output position by its corresponding scalar denominator.
The Order of Operations Matters
The formula highlights the critical insight: the order in which we perform matrix multiplications determines the complexity. Consider the numerator :
-
If we compute first (as in standard attention), we get an matrix. Multiplying by then costs .
-
If we compute first (the linear attention approach), we get a matrix. Multiplying by this costs only .
The second approach avoids ever creating the matrix. This is matrix associativity in action: , but the intermediate sizes differ dramatically.
| Operation | Standard Attention | Linear Attention |
|---|---|---|
| Core computation | ||
| Intermediate matrix | ||
| Complexity | or |
When the feature dimension is proportional to the model dimension (and for long sequences), linear attention provides substantial savings. For a 10,000-token sequence with , standard attention requires a 100-million-element intermediate matrix, while linear attention needs only 4,096 elements.
Implementation: Translating Math to Code
Let's implement linear attention step by step, mapping each line of code to the mathematical operations we've discussed.
import numpy as np
def linear_attention(Q, K, V, feature_map=None, eps=1e-6):
"""
Compute linear attention using the associative property.
Args:
Q: Query matrix of shape (n, d_k)
K: Key matrix of shape (n, d_k)
V: Value matrix of shape (n, d_v)
feature_map: Function to apply to Q and K. If None, uses ELU + 1.
eps: Small constant for numerical stability
Returns:
Output of shape (n, d_v)
"""
if feature_map is None:
# ELU + 1 ensures non-negative features (commonly used)
feature_map = lambda x: np.maximum(x, 0) + np.exp(np.minimum(x, 0))
# Apply feature map to queries and keys
Q_prime = feature_map(Q) # (n, d_k)
K_prime = feature_map(K) # (n, d_k)
# Compute the key-value aggregate: K'^T @ V
# Shape: (d_k, d_v)
KV = K_prime.T @ V
# Compute the key aggregate for normalization: sum of K' along sequence
# Shape: (d_k,)
K_sum = K_prime.sum(axis=0)
# Compute outputs using the efficient formulation
# Numerator: Q' @ KV, shape (n, d_v)
numerator = Q_prime @ KV
# Denominator: Q' @ K_sum, shape (n,)
denominator = Q_prime @ K_sum + eps
# Normalize each position
output = numerator / denominator[:, np.newaxis]
return outputThe implementation follows our derivation exactly:
-
Apply the feature map: Transform and to get and . We use ELU+1 as a default because it ensures all features are positive, which is necessary for the normalization to produce valid weights.
-
Compute the key-value aggregate:
K_prime.T @ Vcomputes , the matrix that summarizes how each feature dimension relates to the values. This is computed once and reused for all queries. -
Compute the normalization aggregate:
K_prime.sum(axis=0)computes , equivalent to . This is the denominator's aggregate. -
Query the aggregates: Each query retrieves its output by multiplying against the precomputed aggregates. The numerator
Q_prime @ KVand denominatorQ_prime @ K_sumare both operations. -
Normalize: Element-wise division produces the final attention output.
Seeing the Efficiency Gain
Let's run this implementation and verify that it produces the expected shapes and efficiency characteristics.
# Demonstrate the efficiency difference
n, d = 128, 64
Q = np.random.randn(n, d).astype(np.float32)
K = np.random.randn(n, d).astype(np.float32)
V = np.random.randn(n, d).astype(np.float32)
output = linear_attention(Q, K, V)Input shapes: Q=(128, 64), K=(128, 64), V=(128, 64) Output shape: (128, 64) Key computation: K'^T @ V creates a 64x64 matrix Standard attention would create a 128x128 matrix Ratio: 4.0x smaller intermediate representation
The output confirms the efficiency gain: instead of a 128×128 attention matrix (16,384 elements), linear attention uses a 64×64 key-value aggregate (4,096 elements). This 4x reduction might seem modest, but remember that the ratio scales as . At 1,024 tokens with , the reduction is 256x. At 8,192 tokens, it's over 16,000x. The quadratic-to-linear improvement becomes increasingly dramatic as sequences grow longer.