Linear Attention › Kernel Feature Maps

Michael BrenndoerferUpdated June 28, 20257 min read
Language AI HandbookAll chapters
Part 17 of 67Efficient Attention
Chapter 123Linear Attention › Kernel Feature Maps
Reading section 4 of 15 · Kernel Feature Maps · 7 minSection 4 of 15 · 7 min

Book contents

Section 4 of 15 · 7 min read

Linear Attention › Kernel Feature MapsOne section · Sections in this chapter4 / 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

The choice of feature map ϕ\phi determines the properties of linear attention. Different feature maps approximate different similarity functions, each with trade-offs between computational efficiency and how well they mimic softmax behavior.

The Kernel Interpretation

The connection between feature maps and attention kernels comes from the theory of reproducing kernel Hilbert spaces (RKHS). A kernel function κ(x,y)\kappa(x, y) measures similarity between two vectors, and Mercer's theorem tells us that any positive semi-definite kernel can be written as:

κ(x,y)=⟨ϕ(x),ϕ(y)⟩\kappa(x, y) = \langle \phi(x), \phi(y) \rangle

where:

  • κ:Rd×Rd→R\kappa: \mathbb{R}^d \times \mathbb{R}^d \to \mathbb{R}: a kernel function that takes two vectors and returns a scalar similarity score
  • x,y∈Rdx, y \in \mathbb{R}^d: input vectors to compare
  • ϕ:Rd→RD\phi: \mathbb{R}^d \to \mathbb{R}^D: a feature map that lifts inputs to a (possibly infinite-dimensional) feature space
  • ⟨⋅,⋅⟩\langle \cdot, \cdot \rangle: the inner product in the feature space

This result, known as Mercer's theorem, tells us that for any valid kernel function, there exists a corresponding feature map. Choosing a feature map implicitly defines a similarity kernel, and vice versa.

Standard softmax attention uses an exponential kernel (ignoring the scaling factor):

κsoftmax(q,k)=exp⁡(qTk)\kappa_{\text{softmax}}(q, k) = \exp(q^T k)

where qTkq^T k is the dot product between query and key vectors. The exponential function ensures the similarity is always positive and amplifies differences between scores.

To approximate this with linear attention, we need a feature map ϕ\phi such that:

ϕ(q)Tϕ(k)≈exp⁡(qTk)\phi(q)^T \phi(k) \approx \exp(q^T k)

Finding such a feature map is the central challenge of linear attention design. The closer the approximation, the more closely linear attention mimics softmax behavior.

Common Feature Maps

Several feature maps have been proposed, each with different properties:

1. ELU + 1 (Efficient Linear Units)

ϕ(x)=ELU(x)+1={x+1if x>0exif x≤0\phi(x) = \text{ELU}(x) + 1 = \begin{cases} x + 1 & \text{if } x > 0 \\ e^x & \text{if } x \leq 0 \end{cases}

This simple feature map ensures all features are positive (required for the normalization to work properly). It doesn't approximate the exponential kernel well but is computationally cheap.

2. ReLU

ϕ(x)=max⁡(0,x)\phi(x) = \max(0, x)

Even simpler than ELU, but can produce zero features, potentially causing numerical issues in the denominator.

3. Random Fourier Features (Performer)

ϕ(x)=1m[sin⁡(ω1Tx),cos⁡(ω1Tx),…,sin⁡(ωmTx),cos⁡(ωmTx)]\phi(x) = \frac{1}{\sqrt{m}} \left[ \sin(\omega_1^T x), \cos(\omega_1^T x), \ldots, \sin(\omega_m^T x), \cos(\omega_m^T x) \right]

where:

  • x∈Rdkx \in \mathbb{R}^{d_k}: the input vector (query or key)
  • mm: the number of random frequency vectors
  • ωi∈Rdk\omega_i \in \mathbb{R}^{d_k}: random frequency vectors sampled from a standard normal distribution N(0,I)\mathcal{N}(0, I)
  • ωiTx\omega_i^T x: the projection of input onto the ii-th random direction
  • 1m\frac{1}{\sqrt{m}}: normalization factor to control the variance of the approximation

The output has dimension 2m2m (sine and cosine for each frequency). This provides an unbiased approximation to the Gaussian kernel. With additional scaling, it can approximate the softmax kernel.

4. Positive Random Features (FAVOR+)

To ensure non-negativity while approximating the exponential kernel, Performer uses:

ϕ(x)=exp⁡(−∥x∥2/2)m[exp⁡(ω1Tx),…,exp⁡(ωmTx)]\phi(x) = \frac{\exp(-\|x\|^2/2)}{\sqrt{m}} \left[ \exp(\omega_1^T x), \ldots, \exp(\omega_m^T x) \right]

where:

  • x∈Rdkx \in \mathbb{R}^{d_k}: the input vector
  • ∥x∥2=∑i=1dkxi2\|x\|^2 = \sum_{i=1}^{d_k} x_i^2: the squared Euclidean norm of the input
  • exp⁡(−∥x∥2/2)\exp(-\|x\|^2/2): a normalization factor that depends on the input magnitude
  • ωi∼N(0,I)\omega_i \sim \mathcal{N}(0, I): random projection vectors sampled from a standard normal distribution
  • exp⁡(ωiTx)\exp(\omega_i^T x): ensures all features are strictly positive
  • mm: the number of random features

This construction gives E[ϕ(q)Tϕ(k)]=exp⁡(qTk)\mathbb{E}[\phi(q)^T \phi(k)] = \exp(q^T k), an unbiased estimator of the softmax kernel. The key insight is that by using exponentials instead of sines and cosines, all features remain positive, which is necessary for the normalization in attention to work correctly.

In[6]:
Code
def elu_feature_map(x):
    """ELU + 1 feature map: simple, always positive."""
    return np.maximum(x, 0) + np.exp(np.minimum(x, 0))


def relu_feature_map(x):
    """ReLU feature map: simplest possible, but can be zero."""
    return np.maximum(x, 0)


def random_fourier_features(x, random_matrix, scale=1.0):
    """
    Random Fourier features for approximating Gaussian/softmax kernel.

    Args:
        x: Input of shape (..., d)
        random_matrix: Random projection matrix of shape (d, m)
        scale: Scaling factor for input

    Returns:
        Features of shape (..., 2m)
    """
    projection = x @ random_matrix * scale
    return np.concatenate(
        [np.sin(projection), np.cos(projection)], axis=-1
    ) / np.sqrt(random_matrix.shape[1])


def positive_random_features(x, random_matrix):
    """
    Positive random features (FAVOR+) for unbiased softmax approximation.

    Args:
        x: Input of shape (..., d)
        random_matrix: Random projection matrix of shape (d, m)

    Returns:
        Features of shape (..., m)
    """
    # Normalize input
    norm_sq = np.sum(x**2, axis=-1, keepdims=True)
    projection = x @ random_matrix

    # Positive features with normalization factor
    features = np.exp(projection - norm_sq / 2)
    return features / np.sqrt(random_matrix.shape[1])
In[7]:
Code
# Compare feature dimensions
d = 64
m = 128  # Number of random features
Out[8]:
Console
Feature Map Comparison:

Feature Map               Input Dim    Output Dim  
--------------------------------------------------
ELU + 1                   64           64          
ReLU                      64           64          
Random Fourier            64           256         
Positive Random (FAVOR+)  64           128

The ELU and ReLU maps preserve the input dimension, making them computationally efficient. Random feature maps expand to a higher dimension, trading compute for better approximation of the softmax kernel.

Out[9]:
Visualization
Line plot comparing ELU+1 and ReLU feature maps across input range from -3 to 3, showing ELU's smooth positive output versus ReLU's hard clipping at zero.
Element-wise feature map transformations. ELU+1 smoothly maps all values to positive outputs, while ReLU clips negative values to zero. The dashed diagonal shows the identity function for reference.
Line plot comparing kernel approximations showing exponential kernel growing rapidly while ELU and ReLU approximations remain more modest.
Kernel approximation quality: similarity values produced by each feature map compared to the true exponential kernel. ELU+1 provides a reasonable approximation for small dot products but diverges for larger values.

The visualizations reveal key properties of the feature maps. ELU+1 produces strictly positive outputs for all inputs, which is essential for attention normalization. ReLU is simpler but zeros out negative inputs, losing information and potentially causing numerical issues. Neither simple feature map accurately approximates the exponential kernel, especially for larger dot products, which explains why they produce different attention patterns than softmax.