AI Logic

Positional Encodings

KERPLE

Updated:

How KERPLE works. The left side shows the flow of an attention layer: no position is added to the input, and in each layer a learned distance penalty βˆ’r₁·log(1 + rβ‚‚|m βˆ’ n|) is added to the score qΒ·k before the softmax. r₁ and rβ‚‚ are learned per head and shared across all layers. The upper right shows the penalty matrix for length 6 with r₁ = rβ‚‚ = 1: the diagonal is 0, and the penalty grows ever more slowly, βˆ’0.69 at distance 1 and βˆ’1.79 at distance 5. The lower right plots the penalty by distance: the straight lines with the same shape as ALiBi drop sharply at long distances, while the logarithmic penalty flattens out

What Is KERPLE

KERPLE (Kernelized Relative Positional Embedding for Length Extrapolation) is a relative position scheme that adds a learned penalty, defined as a function of the position difference, to the attention scores, so that accuracy holds on sequences longer than in training. It was proposed by Chi, Fan, Ramadge, and Rudnicky in 2022 (NeurIPS 2022).

ALiBi showed that simply subtracting a distance-proportional penalty from the scores makes a model robust on sequences longer than in training. The KERPLE paper views this penalty as a kind of kernel (a function measuring how close two positions are) and works out "what shapes of penalty are theoretically sound and robust on long sequences." As a result, ALiBi becomes a special case of the framework, and two new variants are derived: a logarithmic variant and a power variant.

The practical conclusion is that the logarithmic variant βˆ’r1log⁑(1+r2∣mβˆ’n∣)-r_1 \log(1 + r_2|m-n|) works best. With only two learned parameters per head, it achieved lower perplexity than ALiBi, the T5 relative position bias, and RoPE on three large datasets at lengths of 8x the training length (4096) and beyond.

The left side of the figure at the top of the article shows where position information is injected. It uses the same layout as the figure in the ALiBi article; only the shape of the penalty added to the scores differs. The upper right shows the penalty matrix of the logarithmic variant, and the lower right is a plot comparing the penalty by distance with the ALiBi shape (the power variant with r2=1r_2 = 1). The parameters in the figure are illustrative examples; the actual values are determined by training.

Theory (Adding a Kernel of the Position Difference to the Scores)

The explanation follows the equations in Sections 3–4 of the paper. Let the query be qmq_m, the key knk_n, and the head dimension dd.

  1. For each head, prepare learned parameters r1,r2r_1, r_2 (shared across all layers).
  2. In each layer, compute the query–key dot product qm⊀knq_m^\top k_n. No position is added to the input embeddings.
  3. Compute the penalty k~(m,n)\tilde{k}(m, n) from the position difference ∣mβˆ’n∣|m - n| and add it to the dot product.
  4. Divide by d\sqrt{d}, apply softmax, and sum the values.

Combining steps 2–4, the attention weights are given by the following expression (Eq. (1) in the paper).

am,n=exp⁑ ⁣((qm⊀kn+k~(m,n))/d)βˆ‘iexp⁑ ⁣((qm⊀ki+k~(m,i))/d)a_{m,n} = \frac{\exp\!\left(\left(q_m^\top k_n + \tilde{k}(m, n)\right)/\sqrt{d}\right)}{\sum_{i} \exp\!\left(\left(q_m^\top k_i + \tilde{k}(m, i)\right)/\sqrt{d}\right)}

The paper actually tested the following two penalties (cc is a constant explained below).

Logarithmic:Β β€…β€Šcβˆ’r1log⁑(1+r2∣mβˆ’n∣)(r1,r2>0)\text{Logarithmic: }\; c - r_1 \log\left(1 + r_2 |m - n|\right) \quad (r_1, r_2 > 0) Power:Β β€…β€Šcβˆ’r1∣mβˆ’n∣r2(r1>0,β€…β€Š0<r2≀2)\text{Power: }\; c - r_1 |m - n|^{r_2} \quad (r_1 > 0,\; 0 < r_2 \le 2)

Setting r2=1r_2 = 1 in the power variant and fixing r1r_1 instead of learning it gives exactly ALiBi. The upper right of the figure at the top of the article shows the penalty matrix of the logarithmic variant with r1=r2=1r_1 = r_2 = 1. The penalty is βˆ’0.69-0.69 at distance 1 and only βˆ’1.79-1.79 at distance 5; the farther the distance, the more slowly the penalty grows.

Why a "kernel"? The term qm⊀knq_m^\top k_n in attention is a dot product, and dot products are the canonical positive definite kernels (PD kernels). A function such as βˆ’βˆ£mβˆ’n∣-|m - n|, "distance with a minus sign," is not positive definite; it belongs to a class called conditionally positive definite kernels (CPD kernels). The paper shows that adding a sufficiently large constant cc to a CPD kernel makes it positive definite (Lemma 1). Moreover, since softmax is unchanged when the same constant is added to all scores, there is no need to compute the value of cc, and implementations can omit cc. In this way, the sum of the dot product (non-positional) and the positional kernel can be interpreted as a single positive definite kernel.

CPD kernels remain CPD under scaling by a constant, addition, and also under βˆ’(βˆ’k~)Ξ±-(-\tilde{k})^{\alpha} (0<Ξ±<10 < \alpha < 1) and βˆ’log⁑(1βˆ’k~)-\log(1 - \tilde{k}) (Facts 2 and 3 in the paper). Applying these operations to βˆ’βˆ£mβˆ’n∣p-|m-n|^{p} (0<p≀20 < p \le 2) yields the two variants, power and logarithmic.

Why the Logarithmic Penalty Handles Long Sequences Well

The paper explains why the logarithmic variant is robust on long sequences in terms of the penalty's shape.

  • The penalty flattens at long distances: a straight-line penalty like ALiBi's grows at the same rate as distance increases, so distant words quickly become invisible. The logarithmic penalty grows steeply nearby and gently far away, so distant words differ little from each other and distant information remains usable. When the learned penalties are plotted, several heads in the logarithmic variant have flat kernels, which the paper likens to "attention with a wide window."
  • The penalty shape can adapt to the data: ALiBi's slopes are fixed in advance, so the penalty is the same for every dataset. When the paper counted, per head, the distance at which the penalty falls below βˆ’2-2 (the effectively visible range), ALiBi was the same regardless of data, whereas KERPLE differed by dataset. For example, on OpenWebText2, which has high perplexity, more heads looked far away.

The logarithmic variant is also similar to the T5 relative position bias. T5 learns a value per distance on a "logarithmic scale" that groups farther distances into wider buckets. The KERPLE logarithmic variant can be seen as a smooth two-parameter version of this, needing only two parameters per head (T5 uses 32). However, because the logarithm is monotonic, it cannot express non-monotonic relationships such as "attend strongly only at a certain distance," which T5 can.

On the other hand, the paper's appendix shows that using a Gaussian kernel (of the form exp⁑(βˆ’βˆ£mβˆ’n∣2)\exp(-|m-n|^2)), as in prior work, as the penalty degraded sharply on sequences longer than in training. A Gaussian kernel has a limited range of values (it is bounded), so the penalty stops growing as distance increases. The paper argues that choosing a CPD kernel that grows without bound with distance is necessary for length extrapolation.

Experimental Results

Evaluation on sequences longer than in training (Table 3 in the paper): a small GPT-NeoX configuration (12 layers, 12 heads, head dimension 64, 162M parameters) was trained for 50,000 steps at length 512, and perplexity was measured at increasing lengths (lower is better; average over 5 random seeds). The table below shows the OpenWebText2 results.

Evaluation lengthKERPLE (log)KERPLE (power)ALiBiT5 relative position biasRoPESinusoidal
512 (same as training)23.923.923.923.724.233
204821.621.922.521.762.45507
819221.321.622.325.518522621
1638421.421.622.531.426930046

The GitHub and arXiv data show the same trend: perplexity at 16384 was log 2.75, ALiBi 3.02, and T5 3.35 on GitHub, and log 5.07, ALiBi 5.78, and T5 6.25 on arXiv. The T5 relative position bias matched or slightly beat the logarithmic variant at lengths up to 2048 but degraded beyond that.

Training speed (Table 4, GitHub): seconds per step.

KERPLE (log)KERPLE (power)ALiBiT5 relative position biasRoPESinusoidal
0.3070.3210.3020.3400.3320.298

The logarithmic variant was only 1.6% slower than ALiBi and 9.7% faster than the T5 relative position bias.

Comparison in the ALiBi codebase (Table 10 in the appendix): using the same code and settings as the ALiBi paper (247M parameters), only the position representation was changed and compared on WikiText-103.

Training length β†’ evaluation length512 β†’ 512512 β†’ 1024512 β†’ 2048512 β†’ 30722048 β†’ 3072
ALiBi19.7318.8118.4818.4017.64
KERPLE (log)19.6918.7618.2918.2417.56

Larger models (Table 9 in the appendix): with a 1.3B-parameter model as well, the logarithmic variant achieved lower perplexity than ALiBi and the T5 relative position bias on GitHub and arXiv. On OpenWebText2, it was on par with or slightly worse than ALiBi at long lengths.

Practical Considerations

Because the KERPLE penalty is learned, it can overfit the training data depending on the data and model size. The paper offers this as the reason why the logarithmic variant failed to beat ALiBi at long lengths with the 1.3B-parameter model on OpenWebText2 (noisy data that is easy to overfit). ALiBi with its fixed penalty can be more stable in some settings, so compare them on the actual data before choosing.

Other points to keep in mind:

  • Keep the parameters positive: unless r1,r2>0r_1, r_2 > 0 (and r2≀2r_2 \le 2 for the power variant), the penalty is not a CPD kernel and can take strange shapes in which farther positions get smaller penalties. The official implementation clamps r1,r2r_1, r_2 to at least 0.01 after every update.
  • A causal language model is assumed: following ALiBi, the paper's experiments use language models that do not look at future words. Because the penalty is defined by ∣mβˆ’n∣|m - n|, it can also be computed bidirectionally, but the paper does not evaluate this.
  • More complex penalties do not improve much: the paper also tried a logarithmic variant with three parameters and a variant that weights the dot product, but the perplexity gains were small and training became slower. It concludes that the two-parameter logarithmic variant offers a good balance between accuracy and speed.

Comparison with Other Position Representations

MethodWhere position is injectedLearned parametersSequences longer than the training lengthTypical use
Learned positional embeddingAdded to the input embeddings (once)Yes (Lmax⁑×dL_{\max} \times d)Cannot be representedBERT, GPT
Sinusoidal positional encodingAdded to the input embeddings (once)NoneValues can be computed, but accuracy drops sharplyOriginal Transformer
T5 relative position biasA learned scalar per distance bucket added to the scores in each layerYes (32 buckets Γ— number of heads, shared across layers)Improves up to about 2xT5, mT5
RoPEQueries and keys in each layer rotated by an angle proportional to positionNoneOnly slightly longerLLaMA and others
ALiBiA distance-proportional penalty subtracted from the scores in each layerNone (slopes are fixed)Tends to keep accuracyWhen using sequences longer than in training
KERPLE (this article)A penalty proportional to the log of distance added to the scores in each layerYes (2 per head, shared across layers)In the paper, little degradation even at 32x the length, with slightly lower perplexity than ALiBiWhen using sequences longer than in training
  • To gain even a bit more accuracy than ALiBi on sequences longer than in training, the KERPLE logarithmic variant is a candidate. It adds only two parameters per head, and its speed is nearly the same as ALiBi.
  • For stable results without data-specific tuning, ALiBi with its fixed penalty is the easy choice. With large models or noisy data, ALiBi was sometimes more stable.
  • When accuracy at the training length matters most, the T5 relative position bias is also a strong option. In the paper's comparison, T5 matched or slightly beat the others at short lengths, although training is about 10% slower.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F


class KerpleLogBias(nn.Module):
    """Logarithmic variant of KERPLE: adds -r1 * log(1 + r2 * |m - n|) to the scores (Section 4 of the paper; the constant c is omitted)"""

    def __init__(self, n_heads: int, eps: float = 1e-2):
        super().__init__()
        self.r1 = nn.Parameter(torch.rand(n_heads) * 2)    # 2 per head; one instance is shared across layers
        self.r2 = nn.Parameter(torch.rand(n_heads))
        self.eps = eps

    def forward(self, seq_len: int) -> torch.Tensor:
        r1 = self.r1.clamp(min=self.eps)[:, None, None]    # keep r1, r2 > 0 (the official implementation also clamps at 0.01)
        r2 = self.r2.clamp(min=self.eps)[:, None, None]
        pos = torch.arange(seq_len)
        dist = (pos[:, None] - pos[None, :]).float()        # m - n (query m, key n)
        bias = -r1 * torch.log1p(r2 * dist.clamp(min=0))    # [n_heads, seq_len, seq_len]
        return bias.masked_fill(dist < 0, float("-inf"))   # hide future positions


B, h, n, d = 2, 12, 512, 64
rpe = KerpleLogBias(h)                                      # one for the whole model (shared across all layers)
q, k, v = (torch.randn(B, h, n, d) for _ in range(3))
# Eq. (1) of the paper is (q·k + penalty) / √d. attn_mask is added after q·k / √d, so pass the penalty divided by √d as well
out = F.scaled_dot_product_attention(q, k, v, attn_mask=rpe(n) / d ** 0.5)
print(out.shape)                                            # torch.Size([2, 12, 512, 64])

# For sequences longer than in training, just build the penalty with the same parameters
n_long = 2048
q, k, v = (torch.randn(1, h, n_long, d) for _ in range(3))
out = F.scaled_dot_product_attention(q, k, v, attn_mask=rpe(n_long) / d ** 0.5)
print(out.shape)                                            # torch.Size([1, 12, 2048, 64])

FAQ

Q. How does it differ from ALiBi?
A.

ALiBi subtracts a distance-proportional penalty βˆ’m∣mβˆ’n∣-m|m-n| with a fixed slope mm. KERPLE generalizes this penalty as a kind of CPD kernel, allowing its shape to change (logarithmic, power) and its coefficients to be learned. Setting r2=1r_2 = 1 in the power variant and fixing r1r_1 gives exactly ALiBi. In the paper's comparison, the logarithmic variant achieved lower perplexity than ALiBi on sequences longer than in training.

Q. Should the logarithmic or the power variant be used?
A.

The paper's conclusion is the logarithmic variant. On all three datasets and at all lengths, it had lower perplexity than the power variant, and it trained 4.4% faster. Looking at the learned penalties, the power variant, like ALiBi, quickly becomes strongly negative at long distances, whereas the logarithmic variant had more heads that look far away.

Q. How is the constant $c$ added to the penalty chosen?
A.

It does not need to be chosen. cc is a theoretical constant that allows the penalty to be interpreted as a positive definite kernel. Since softmax is unchanged when the same constant is added to all scores, implementations omit cc and add only βˆ’r1log⁑(1+r2∣mβˆ’n∣)-r_1 \log(1 + r_2|m-n|).

References

  1. T.-C. Chi, T.-H. Fan, P. J. Ramadge, and A. I. Rudnicky, "KERPLE: Kernelized Relative Positional Embedding for Length Extrapolation," NeurIPS, 2022.
  2. O. Press, N. A. Smith, and M. Lewis, "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation," ICLR, 2022.
  3. chijames/KERPLE (official implementation of the paper)