AI Logic

Positional Encodings

ALiBi

Updated:

How ALiBi works. The left side shows the flow of an attention layer: no position is added to the input, and in each layer a penalty proportional to distance, βˆ’mΒ·(i βˆ’ j), is added to the score qΒ·k before the softmax. The upper right shows the bias matrix for length 6 and a head with slope m = 1/2: the diagonal is 0, each step away decreases the value by 0.5, and future positions in the upper right are masked. The lower right lists the slopes 1/2 to 1/256 for 8 heads

What Is ALiBi

ALiBi (Attention with Linear Biases) injects position information by adding a negative value (a penalty) proportional to the query–key distance to the attention scores. It was proposed by Press, Smith, and Lewis in 2021 (ICLR 2022). No position embedding is added anywhere in the network, and there are no learned parameters.

The goal of ALiBi is that accuracy does not collapse when inference runs on sequences longer than those seen in training. Language models predict better the longer the context they see, but training on long sequences costs time and memory. The paper shows that models with sinusoidal positional encoding start to degrade once the input is only a few dozen tokens longer than in training, and that RoPE and the T5 relative position bias are not sufficient either (the T5 scheme extrapolates but trains slowly), before proposing ALiBi.

The penalty grows with the distance of the key. The mechanism gives the model a built-in tendency to "weight nearby words more," and because the same rule computes the penalty however far the distance extends, it applies directly to lengths never seen in training.

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 figures in the learned positional embedding, relative position representations, and RoPE articles, so the injection points can be compared side by side. The right side shows the matrix of penalty values (the bias) and the per-head slopes.

Theory (Adding a Distance-Proportional Penalty to the Scores)

The explanation follows the equations in Section 3 of the paper. Consider a language model (causal attention that does not look at future words) in which the ii-th query qiq_i attends to the keys KK at positions 11 to ii.

  1. Compute the scores as usual with the query–key dot product qiK⊀q_i K^\top. No position is added to the input embeddings.
  2. Choose one slope mm per head. mm is not learned; it is fixed to a value chosen before training.
  3. For each key, subtract the distance from the query iβˆ’ji - j multiplied by mm from the score. The query itself (distance 0) gets 0, the previous position gets βˆ’m-m, and the one before that gets βˆ’2m-2m.
  4. Apply softmax to obtain the weights and sum the values (as in ordinary attention).

Steps 1–4 combine into the following expression.

softmax(qiK⊀+mβ‹…[βˆ’(iβˆ’1),…,βˆ’2,βˆ’1,0])\mathrm{softmax}\Bigl(q_i K^\top + m \cdot \bigl[-(i-1), \dots, -2, -1, 0\bigr]\Bigr)

With nn heads, the slopes in step 2 form a geometric sequence that starts at 2βˆ’8/n2^{-8/n} and uses the same 2βˆ’8/n2^{-8/n} as the ratio.

mh=(2βˆ’8/n)h=2βˆ’8h/n,h=1,2,…,nm_h = \left(2^{-8/n}\right)^{h} = 2^{-8h/n}, \qquad h = 1, 2, \dots, n

With 8 heads this gives 12,14,…,1256\frac{1}{2}, \frac{1}{4}, \dots, \frac{1}{256}; with 16 heads, 120.5,12,121.5,…,1256\frac{1}{2^{0.5}}, \frac{1}{2}, \frac{1}{2^{1.5}}, \dots, \frac{1}{256}. The upper right of the figure at the top of the article shows the bias matrix computed for a sequence of length 6 and a head with m=1/2m = 1/2. The diagonal is 0, and each step to the left decreases the value by 0.5.

The penalty is added to the scores after the dot product is divided by dk\sqrt{d_k}, not before (footnote 10 of the paper). In practice, adding the penalty to the mask matrix that a language model already uses to hide future words avoids any extra computation in the network (Implementation in Section 3 of the paper).

Why It Handles Long Sequences Well

The ALiBi penalty is a simple straight line determined only by distance. Keys farther away than any distance seen in training simply receive a penalty from the same line extended further, so even with long inputs the score values are unlikely to jump into a range never seen during training. As an analogy with radio, more distant stations sound quieter; however many distant stations are added, nearby stations sound the same.

Using a different slope for each head is another part of the design. Heads with a large slope (such as m=1/2m = 1/2) attend only to nearby words, while heads with a small slope (such as m=1/256m = 1/256) attend to distant words as well. The paper tried about 10 sets of slopes and found that sets in the range 00 to 11 that are denser near 0 work best. It reports that the method is robust to the choice of slopes, and in some cases slopes drawn at random from an exponential distribution also worked well. Learning the slopes, on the other hand, gave poor extrapolation results.

Like RoPE and the T5 relative position bias, ALiBi injects position information only into the queries and keys (the scores) of each layer, not into the values. The paper suggests that this separation helps extrapolation.

However, according to the analysis in Appendix B of the paper, the lower perplexity on sequences longer than in training may not come from actually using the longer context. When evaluation splits text into segments, the first words of each segment can see almost no preceding context (the paper calls this the early token curse). Evaluating with longer sequences reduces the proportion of such words. When the evaluation was redone with a stride of one token so that every word gets the maximum context, ALiBi's perplexity did not improve with longer lengths and stayed nearly flat.

Experimental Results

Evaluation on sequences longer than in training (Table 2 in the paper's appendix): perplexity on WikiText-103 of language models trained on sequences of length L=512L = 512 and evaluated on longer sequences (lower is better).

Evaluation lengthSinusoidalRoPET5 relative position biasALiBi
512 (same as training)20.0520.0719.6519.73
101243.5421.3718.7918.73
3512178.9735.5422.9118.40
15512406.0179.25Out of memory18.31

Sinusoidal and RoPE degrade sharply as the length grows, and the T5 relative position bias also degrades beyond about 2x, while ALiBi did not degrade even at 30x the length.

Train short, test long (Section 4.1 and Table 5 in the appendix): comparison on the WikiText-103 development set with the evaluation length fixed at 3072.

ModelTraining length LLPerplexity
Sinusoidal307218.67
RoPE307218.57
T5 relative position bias307218.01
ALiBi51218.40
ALiBi307217.60

ALiBi trained on length 512 outperformed the sinusoidal model trained on 6x the length. Training was 1.84x faster and required less memory. When trained on the same length of 3072, ALiBi achieved the best value.

Larger models (Section 4.2): a 1.3B-parameter model was trained on 461 GB of text (the RoBERTa training data plus the English part of CC-100). Evaluated at length 2048, the ALiBi model trained on length 1024 had 0.09 lower perplexity than the sinusoidal model trained on length 2048, while using 3.1 GB less memory. The paper's abstract states that it reached the same perplexity 11% faster and with 11% less memory. On this data, however, extrapolation kept improving only up to about 2x the training length.

Practical Considerations

With ALiBi, accuracy rarely collapses on sequences longer than in training, but the model does not necessarily make real use of context longer than in training. In the paper's analysis, when every word was given the maximum context, perplexity stayed nearly flat as the length increased. Treat "handling long inputs safely" and "making better predictions using distant information" as separate questions, and verify on the actual task when it requires understanding long contexts.

Other points to keep in mind:

  • Do not learn the slopes: in the paper, learning the slopes gave poor extrapolation results and made training 3% slower. The geometric sequence based on 2βˆ’8/n2^{-8/n} is said not to need retuning when the data or model size changes.
  • The mask matrix gets somewhat larger: an ordinary mask is LΓ—LL \times L, but because ALiBi uses a different slope for each head, it becomes nΓ—LΓ—Ln \times L \times L. In the paper's experiments, memory grew by up to about 100 MB. Because training can use shorter sequences, the overall savings amount to several GB.
  • The penalty is also a bias toward nearby words: on large-scale data, accuracy at the training length was almost the same as sinusoidal. The paper suggests that ALiBi's inductive bias may be more useful for language models on smaller data.

The ALiBi bias is defined for keys 11 to ii, assuming a causal (non-lookahead) language model. The PyTorch example below combines the penalty and the future mask into one matrix and passes it to the attn_mask argument of scaled_dot_product_attention.

Comparison with Other Position Representations

MethodWhere position is injectedLearned parametersSequences longer than the training lengthTraining/inference speed (comparison in the ALiBi paper)
Learned positional embeddingAdded to the input embeddings (once)Yes (Lmax⁑×dL_{\max} \times d)Cannot be representedβ€”
Sinusoidal positional encodingAdded to the input embeddings (once)NoneDegrades a few dozen tokens beyondBaseline
Relative position representationsPer-distance vectors added to the scores and values in each layerYes (2k+12k+1 distances)Computable because distances are clippedβ€”
T5 relative position biasA learned scalar per distance added to the scores in each layerYesImproves up to about 2xTraining more than 2x slower than sinusoidal
RoPEQueries and keys in each layer rotated by an angle proportional to positionNoneOnly slightly longerSlower than sinusoidal (with the paper's implementation)
ALiBi (this article)A distance-proportional penalty subtracted from the scores in each layerNoneNo degradation even at 30x the lengthAbout the same as sinusoidal
  • To train cheaply on short sequences and handle longer inputs at inference, ALiBi is a good fit.
  • To let training flexibly decide how distance matters, there are methods that learn a value per distance, such as the T5 relative position bias. ALiBi fixes the shape to a straight line in exchange for adding no parameters or computation.
  • When using a pretrained model as is, follow the position representation that the model uses. To extend the context of a RoPE model, there are methods such as position interpolation.

PyTorch example

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


def alibi_slopes(n_heads: int) -> torch.Tensor:
    """Per-head slopes m_h = 2^(-8h/n) (geometric sequence starting at 2^(-8/n); Section 3 of the paper)"""
    h = torch.arange(1, n_heads + 1, dtype=torch.float32)
    return 2.0 ** (-8.0 * h / n_heads)                      # with 8 heads: 1/2, 1/4, ..., 1/256


def alibi_bias(n_heads: int, seq_len: int) -> torch.Tensor:
    """Matrix added to the scores [n_heads, seq_len, seq_len]. Future positions are masked with -inf"""
    pos = torch.arange(seq_len)
    dist = (pos[:, None] - pos[None, :]).float()             # i - j (query i, key j)
    bias = -alibi_slopes(n_heads)[:, None, None] * dist      # -m * (i - j)
    future = dist < 0                                        # hide j > i
    return bias.masked_fill(future, float("-inf"))


print(alibi_slopes(8))            # tensor([0.5000, 0.2500, ..., 0.0039])
print(alibi_bias(8, 6)[0])        # first head (m = 1/2): diagonal 0, -0.5 for each step away

# Use in attention: no position embedding is added to the input
B, h, n, d = 2, 8, 16, 64
q, k, v = torch.randn(B, h, n, d), torch.randn(B, h, n, d), torch.randn(B, h, n, d)
# A float matrix passed as attn_mask is added to the scores after q·k / √d (the penalty is not divided by √d)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=alibi_bias(h, n))
print(out.shape)                  # torch.Size([2, 8, 16, 64])

# For sequences longer than in training, just build the bias with the same formula
n_long = 64
q, k, v = (torch.randn(B, h, n_long, d) for _ in range(3))
out = F.scaled_dot_product_attention(q, k, v, attn_mask=alibi_bias(h, n_long))
print(out.shape)                  # torch.Size([2, 8, 64, 64])

FAQ

Q. How should the slope $m$ be chosen?
A.

The default is to use the paper's scheme as is: with nn heads, a geometric sequence that starts at 2βˆ’8/n2^{-8/n} with ratio 2βˆ’8/n2^{-8/n}. The paper reports that these slopes work well across different kinds of text and model sizes without retuning. Learning the slopes gave poor extrapolation results.

Q. Does ALiBi prevent the model from seeing distant words?
A.

The penalty grows in proportion to distance, but it is only subtracted from the score, so distant words can still be attended to if the dot product is large enough. In addition, heads with a small slope (m=1/256m = 1/256 with 8 heads) receive a penalty of only about 0.39 even at distance 100, so they can see far away. However, the paper's analysis leaves it unclear whether context longer than in training is actually being used, and treats this as future work.

Q. Can it be used in encoders (bidirectional attention)?
A.

The paper's equations and experiments target language models (decoders) that do not look at future words. Using it with bidirectional attention requires deciding how to penalize keys that come after the query, which the paper does not address.

References

  1. O. Press, N. A. Smith, and M. Lewis, "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation," ICLR, 2022.
  2. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  3. J. Su, Y. Lu, S. Pan, A. Murtadha, B. Wen, and Y. Liu, "RoFormer: Enhanced Transformer with Rotary Position Embedding," arXiv:2104.09864, 2021.