Algorithm Search⌘K

Techniqueresearch

Attention with linear biases

Also called ALiBi.

Add to each attention score a penalty linear in the distance between query and key, with a fixed slope per head, instead of position vectors.

Attention with linear biases, ALiBi, gives a transformer language model word order without any position vectors. In each head, it subtracts from the score of query ii and key jj a penalty m⋅(i−j)m \cdot (i - j), proportional to how far back the key is. The slope mm is fixed before training and is different in each head, so some heads look mostly at the last few tokens and others look far back. Press, Smith and Lewis introduced it in 2021 to make models work on inputs longer than those seen in training: a model trained on short inputs can then be run on longer ones. Their 1.3B-parameter model trained on 1024 tokens matched, on 2048-token inputs, the perplexity of a sinusoidal model trained on 2048 tokens, while training 11% faster and with 11% less memory (a measurement).

In plain words

In a causal language model, each word looks back at the words before it and decides how much to take from each. ALiBi adds one simple rule: the further back a word is, the more its match score is reduced, by a fixed amount per step.

Each head has its own rate. A head with a high rate sees almost only the last few words. A head with a low rate sees far back. Nothing about position is added to the words themselves.

Because the rule depends only on distance, a word 5 steps back is treated the same at the start of the text and deep into it. And a longer text only adds words that are far back and get little weight, so the model is not surprised by a length it never saw.

When it applies

  • A decoder-only causal language model that should run on inputs longer than its training inputs, or be trained on short inputs to save time and memory.
  • Multi-head attention with a causal mask, where the mask matrix is already added to the scores: the bias goes into the same matrix.
  • Tasks with a recency bias, where nearby tokens matter most, such as language modeling of running text.

The template

Let a head have slope m>0m > 0, keys k1,…,kik_1, \ldots, k_i visible to query qiq_i, and head size dkd_k. The biased score is

sij=qi⋅kjdk−m (i−j),j≤i,s_{ij} = \frac{q_i \cdot k_j}{\sqrt{d_k}} - m\,(i - j), \qquad j \le i,

that is, the row qiK⊤/dkq_i K^\top / \sqrt{d_k} plus m⋅[−(i−1),…,−2,−1,0]m \cdot [-(i-1), \ldots, -2, -1, 0]. The bias is not scaled by 1/dk1/\sqrt{d_k}. Softmax and the weighted sum of values are as in scaled dot-product attention.

  1. ALIBI-HEAD(Q, K, V, m) ▷ causal, slope m of this head
  2. 1for i ← 1 to n do
  3. 2for j ← 1 to i do
  4. 3s_j ← q_i · k_j / sqrt(d_k) - m · (i - j)
  5. 4p ← softmax(s_1, ..., s_i)
  6. 5o_i ← Σ_{j ≤ i} p_j v_j
  7. 6return O = (o_1, ..., o_n)

The slopes. For hh heads, hh a power of 2, the slopes are the geometric sequence that starts at 2−8/h2^{-8/h} with ratio 2−8/h2^{-8/h}: mr=2−8r/hm_r = 2^{-8r/h} for r=1,…,hr = 1, \ldots, h. With 8 heads this is 12,14,…,1256\tfrac12, \tfrac14, \ldots, \tfrac1{256}. With 16 heads it is 2−0.5,2−1,…,2−82^{-0.5}, 2^{-1}, \ldots, 2^{-8}, which puts the geometric mean of each pair of the 8-head slopes between them. For other hh, the code of the authors takes the 2a2^a slopes of the largest power of 2 below hh and fills the rest with every other slope of 2a+12^{a+1} heads.

Row shifts do not matter (theorem). Softmax does not change when the same number is added to every score of a row. Adding m im\,i to row ii turns the bias −m(i−j)-m(i - j) into +m j+m\,j, which depends on the key alone. So the biased head equals a head with the bias m jm\,j plus the causal mask. In practice the bias is stored in the mask matrix, one L×LL \times L matrix per head, and the cost of attention does not change.

Distance only (theorem). The bias of the pair (i,j)(i, j) is the same as that of (i+t,j+t)(i + t, j + t) for every tt. If every scaled product satisfies ∣qi⋅kj∣/dk≤B|q_i \cdot k_j| / \sqrt{d_k} \le B, the weight on a key at distance r=i−jr = i - j is at most e2B−mre^{2B - m r}, since its score exceeds the score of the key at distance 0 by at most 2B−mr2B - m r. The full proof gives both results and the correctness of the procedure.

Cost. As plain causal attention: Θ(n2(dk+dv))\Theta(n^2 (d_k + d_v)) operations per head, with a bias of Θ(1)\Theta(1) per score. No parameters are added.

Classic examples

A worked head. Take one head with slope m=12m = \tfrac12 and all queries and keys equal to zero, so only the bias acts. Values are v1,…,v4=0,1,2,3v_1, \ldots, v_4 = 0, 1, 2, 3. For query 4, the scores are −1.5,−1,−0.5,0-1.5, -1, -0.5, 0, and the weights are

key jj 1 2 3 4
distance 4−j4 - j 3 2 1 0
weight 0.101536 0.167405 0.276004 0.455054

so o4=2.084576o_4 = 2.084576. Each step back multiplies the weight by e−1/2=0.606531e^{-1/2} = 0.606531. The outputs for queries 1 to 4 are 0,0.622459,1.320157,2.0845760, 0.622459, 1.320157, 2.084576; with m=0m = 0 they would be the plain means 0,0.5,1,1.50, 0.5, 1, 1.5.

Length extrapolation. In Figure 1 of Press and colleagues, models trained on WikiText-103 with inputs of 512 or 1024 tokens were tested on longer inputs. The perplexity of the sinusoidal, rotary and T5 bias methods got worse as the inputs grew past the training length, and that of ALiBi did not (a measurement).

Training short and testing long. The 1.3B-parameter model of Section 4, trained on 1024 tokens, reached the perplexity of a sinusoidal model trained on 2048 tokens when both were tested on 2048 tokens (a measurement).

Generation with a cache. With a key-value cache, the new query at position tt gets the biases −m(t−j)-m(t - j) for the cached keys. The bias depends on positions alone, so cached keys need no change, as with rotary position embedding.

Variations

  • Trainable slopes. Press and colleagues tried learned slopes; extrapolation was not strong and training was 3% slower (Section 3, a measurement).
  • Other slope sets. They report that slopes in (0,1)(0, 1), denser near 0, work best, and that the method is not very sensitive to the exact set.
  • Bidirectional use. For an encoder without a causal mask, one choice is the symmetric bias −m ∣i−j∣-m\,|i - j|. This loses the difference between left and right unless the slopes differ by direction.
  • Learned relative biases. The T5 bias learns one bias per distance bucket, shared by the layers. ALiBi replaces this table by a fixed line.
  • With fast kernels. The bias m jm\,j is computed from the indices, so it fits into a tiled kernel such as FlashAttention without storing an L×LL \times L matrix.

Pitfalls

  • Scaling the bias. The bias is added after the scaling by 1/dk1/\sqrt{d_k} and is not itself scaled (footnote 10 of the paper). Scaling it changes the slopes.
  • Adding position vectors as well. ALiBi models add no position vectors at any point. Adding a sinusoidal encoding as well changes the model.
  • Wrong sign. The penalty must decrease the scores of far keys. With the sign flipped, the bias favors the first tokens of the text.
  • Wrong positions with a cache. The new query must use its absolute position tt in the text, not its index in the current chunk.
  • Memory of the bias matrix. Storing a separate L×LL \times L bias per head costs memory, up to 100 MB in the experiments of the paper. Computing the bias from the indices avoids it.
  • Expecting long-range use. Extrapolation here means the perplexity does not blow up. Far tokens get small weights in heads with large slopes, so ALiBi does not by itself make a model use very distant context.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

alibi_attention_bias.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alibi-attention-bias/. The authors are listed in prov/FKDFWV.jsonl.

"""Attention with linear biases (ALiBi) of Press, Smith and Lewis.

One causal attention head with slope m > 0. Query i at position p_i sees the
keys at positions j <= p_i, and its score for key j is

    s_ij = q_i . k_j / sqrt(d_k) - m (p_i - j).

The bias is not scaled by 1/sqrt(d_k). The scores go through a softmax and
weight the values as usual. No position vector is added anywhere.

With n queries and M keys (M >= n), query i (from 0) sits at position
i + (M - n), so the last query is the newest token. M > n is the case of
generation with a key-value cache.

alibi_slopes(h) gives the fixed slopes of h heads: for h a power of 2, the
geometric sequence that starts at 2^(-8/h) with ratio 2^(-8/h). For other h,
the slopes of the largest power of 2 below h, followed by every other slope
of the next power of 2, as in the code of the authors.

Precondition: Q is n x d_k, K is M x d_k, V is M x d_v, 1 <= n <= M, m >= 0.
Cost: Theta(n M (d_k + d_v)) operations, Theta(M) extra memory per query row.
The code takes the queries, keys and values as given. It does not train a network.
"""

import math
from typing import List, Sequence

Matrix = List[List[float]]


def _slopes_power_of_2(h: int) -> List[float]:
    start = 2.0 ** (-8.0 / h)
    return [start ** (r + 1) for r in range(h)]


def alibi_slopes(h: int) -> List[float]:
    """The fixed slopes of h heads, from the largest to the smallest for h a power of 2."""
    if h < 1:
        raise ValueError("h must be at least 1")
    if h & (h - 1) == 0:
        return _slopes_power_of_2(h)
    p = 1 << (h.bit_length() - 1)
    return _slopes_power_of_2(p) + alibi_slopes(2 * p)[0::2][: h - p]


def alibi_bias(n: int, M: int, slope: float) -> Matrix:
    """The n x M bias matrix: -slope (p_i - j) where key j is visible, -inf where it is masked."""
    shift = M - n
    return [[-slope * (i + shift - j) if j <= i + shift else float("-inf") for j in range(M)] for i in range(n)]


def alibi_attention(
    Q: Sequence[Sequence[float]],
    K: Sequence[Sequence[float]],
    V: Sequence[Sequence[float]],
    slope: float,
) -> Matrix:
    """One causal head with the linear bias of the given slope. Returns an n x d_v matrix."""
    n, M = len(Q), len(K)
    if n < 1 or M < n or len(V) != M:
        raise ValueError("need 1 <= n <= M queries and M keys and values")
    dk = len(K[0])
    if any(len(q) != dk for q in Q) or any(len(k) != dk for k in K):
        raise ValueError("queries and keys must have the same size")
    if not slope >= 0:
        raise ValueError("the slope must be non-negative")
    shift = M - n
    scale = 1.0 / math.sqrt(dk)
    out: Matrix = []
    for i in range(n):  # @line L1
        p_i = i + shift
        s = []
        for j in range(p_i + 1):  # @line L2
            s.append(math.fsum(a * b for a, b in zip(Q[i], K[j])) * scale - slope * (p_i - j))  # @line L3
        mu = max(s)
        w = [math.exp(x - mu) for x in s]
        z = math.fsum(w)
        p = [x / z for x in w]  # @line L4
        out.append([math.fsum(p[j] * V[j][c] for j in range(p_i + 1)) for c in range(len(V[0]))])  # @line L5
    return out  # @line L6
test_alibi_attention_bias.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alibi-attention-bias/. The authors are listed in prov/FKDFWV.jsonl.

import math
import random

import pytest

from alibi_attention_bias import alibi_attention, alibi_bias, alibi_slopes


def rand_matrix(rng, rows, cols, scale=1.0):
    return [[rng.gauss(0, scale) for _ in range(cols)] for _ in range(rows)]


def oracle(Q, K, V, bias):
    """Full score matrix plus a bias matrix, then a log-sum-exp softmax per row."""
    dk = len(K[0])
    out = []
    for i, q in enumerate(Q):
        s = [sum(a * b for a, b in zip(q, k)) / math.sqrt(dk) + bias[i][j] for j, k in enumerate(K)]
        mu = max(s)
        lse = mu + math.log(sum(math.exp(x - mu) for x in s if x != float("-inf")))
        p = [math.exp(x - lse) if x != float("-inf") else 0.0 for x in s]
        out.append([sum(p[j] * V[j][c] for j in range(len(V))) for c in range(len(V[0]))])
    return out


def close(A, B, tol=1e-9):
    return all(abs(a - b) <= tol * (1 + abs(b)) for ra, rb in zip(A, B) for a, b in zip(ra, rb))


def test_worked_example():
    Q = [[0.0]] * 4
    K = [[0.0]] * 4
    V = [[0.0], [1.0], [2.0], [3.0]]
    O = alibi_attention(Q, K, V, 0.5)
    assert [round(r[0], 6) for r in O] == [0.0, 0.622459, 1.320157, 2.084576]
    # with slope 0 every visible key gets the same weight
    assert [r[0] for r in alibi_attention(Q, K, V, 0.0)] == pytest.approx([0.0, 0.5, 1.0, 1.5])


def test_slopes():
    assert alibi_slopes(8) == [2.0 ** -k for k in range(1, 9)]
    s16 = alibi_slopes(16)
    assert s16 == pytest.approx([2.0 ** (-k / 2) for k in range(1, 17)])
    # 16 heads interleave the 8 slopes with their geometric means
    assert s16[1::2] == pytest.approx(alibi_slopes(8))
    s12 = alibi_slopes(12)
    assert s12[:8] == alibi_slopes(8)
    assert s12[8:] == pytest.approx([2.0 ** -0.5, 2.0 ** -1.5, 2.0 ** -2.5, 2.0 ** -3.5])
    for h in range(1, 40):
        s = alibi_slopes(h)
        assert len(s) == h and len(set(s)) == h and all(0 < x < 1 for x in s)


@pytest.mark.parametrize("seed", range(12))
def test_against_bias_matrix_oracle(seed):
    rng = random.Random(seed)
    M = rng.randint(1, 9)
    n = rng.randint(1, M)
    dk, dv = rng.randint(1, 5), rng.randint(1, 4)
    Q, K, V = rand_matrix(rng, n, dk), rand_matrix(rng, M, dk), rand_matrix(rng, M, dv)
    slope = rng.choice(alibi_slopes(8))
    assert close(alibi_attention(Q, K, V, slope), oracle(Q, K, V, alibi_bias(n, M, slope)))


@pytest.mark.parametrize("seed", range(8))
def test_row_shift_gives_the_same_output(seed):
    """Adding slope * p_i to row i turns the bias into +slope * j; the softmax does not change."""
    rng = random.Random(100 + seed)
    M = rng.randint(1, 9)
    n = rng.randint(1, M)
    Q, K, V = rand_matrix(rng, n, 3), rand_matrix(rng, M, 3), rand_matrix(rng, M, 2)
    slope = rng.uniform(0, 1)
    shift = M - n
    key_only = [[slope * j if j <= i + shift else float("-inf") for j in range(M)] for i in range(n)]
    assert close(alibi_attention(Q, K, V, slope), oracle(Q, K, V, key_only))


@pytest.mark.parametrize("seed", range(8))
def test_bias_depends_only_on_distance_and_cache_rows_match(seed):
    rng = random.Random(200 + seed)
    M = rng.randint(1, 6)
    t = rng.randint(1, 5)
    slope = rng.choice(alibi_slopes(8))
    small, big = alibi_bias(M, M, slope), alibi_bias(M + t, M + t, slope)
    assert all(small[i][j] == big[i + t][j + t] for i in range(M) for j in range(M))
    # with a key-value cache (n < M) the rows equal the last rows of the full run
    Q, K, V = rand_matrix(rng, M, 3), rand_matrix(rng, M, 3), rand_matrix(rng, M, 2)
    n = rng.randint(1, M)
    assert close(alibi_attention(Q[M - n :], K, V, slope), alibi_attention(Q, K, V, slope)[M - n :])


@pytest.mark.parametrize("seed", range(8))
def test_far_keys_get_small_weight(seed):
    """If every |q . k| / sqrt(d_k) <= B, the weight on a key at distance r is at most exp(2B - m r)."""
    rng = random.Random(300 + seed)
    M, dk = 30, 4
    Q = rand_matrix(rng, M, dk, 0.5)
    K = rand_matrix(rng, M, dk, 0.5)
    slope = rng.choice([0.5, 0.25, 0.125])
    B = max(abs(sum(a * b for a, b in zip(q, k))) / math.sqrt(dk) for q in Q for k in K)
    i = M - 1
    for j in range(M):
        V = [[1.0 if t == j else 0.0] for t in range(M)]
        w = alibi_attention(Q, K, V, slope)[i][0]
        assert w <= math.exp(2 * B - slope * (i - j)) + 1e-12


def test_large_slope_attends_to_self_and_rows_sum_to_one():
    rng = random.Random(7)
    Q, K, V = rand_matrix(rng, 5, 3), rand_matrix(rng, 5, 3), rand_matrix(rng, 5, 2)
    O = alibi_attention(Q, K, V, 1000.0)
    assert close(O, V, 1e-9)
    ones = [[1.0] for _ in range(5)]
    assert all(r[0] == pytest.approx(1.0) for r in alibi_attention(Q, K, ones, 0.3))


def test_errors():
    with pytest.raises(ValueError):
        alibi_slopes(0)
    with pytest.raises(ValueError):
        alibi_attention([[1.0], [1.0]], [[1.0]], [[1.0]], 0.5)
    with pytest.raises(ValueError):
        alibi_attention([[1.0]], [[1.0]], [[1.0]], -0.5)
    with pytest.raises(ValueError):
        alibi_attention([[1.0, 2.0]], [[1.0]], [[1.0]], 0.5)

Exercises

  1. Show that softmax is unchanged when a constant is added to all its inputs, and conclude that the biases −m(i−j)-m(i - j) and +m j+m\,j give the same head.
  2. With all scores equal to zero, show that the weights of query ii form a truncated geometric distribution with ratio e−me^{-m}, and find their limit as i→∞i \to \infty.
  3. Prove the bound: if ∣qi⋅kj∣/dk≤B|q_i \cdot k_j| / \sqrt{d_k} \le B for all pairs, the weight on a key at distance rr is at most e2B−mre^{2B - m r}.
  4. Compute the slopes for h=4h = 4, h=8h = 8 and h=12h = 12 with the rule of the authors, and check that the 16-head slopes interleave the 8-head slopes with their geometric means.
  5. Explain why ALiBi, like rotary position embedding, puts no position information into the values, and what the output of a layer then knows about position.
Proof: ALIBI-HEAD returns the causal softmax attention with scores q_i . k_j / sqrt(d_k) - m (i - j), the head equals one with the key-only bias m j, the bias depends only on i - j, and the weight at distance r is at most exp(2B - m r)full

We use the notation of the page. A head has slope m≥0m \ge 0, queries q1,…,qnq_1, \ldots, q_n, keys k1,…,knk_1, \ldots, k_n and values v1,…,vnv_1, \ldots, v_n. For j≤ij \le i write aij=qi⋅kj/dka_{ij} = q_i \cdot k_j / \sqrt{d_k}, and define the target output

oi∗=∑j≤ieaij−m(i−j)∑l≤ieail−m(i−l) vj.o_i^\ast = \sum_{j \le i} \frac{e^{a_{ij} - m(i - j)}}{\sum_{l \le i} e^{a_{il} - m(i - l)}}\, v_j .

Lemma 1 (the procedure). ALIBI-HEAD returns oi=oi∗o_i = o_i^\ast for every ii.

Proof. Fix ii at line L1. The loop at line L2 visits j=1,…,ij = 1, \ldots, i, so line L3 sets sj=aij−m(i−j)s_j = a_{ij} - m(i - j) for exactly the visible keys. Line L4 sets pj=esj/∑l≤ieslp_j = e^{s_j} / \sum_{l \le i} e^{s_l}, and line L5 forms ∑j≤ipjvj\sum_{j \le i} p_j v_j, which is oi∗o_i^\ast. The rows do not share state, and line L6 returns all of them. □\square

The code subtracts the row maximum μ\mu before the exponentials. This multiplies the numerator and the denominator by e−μe^{-\mu} and does not change pp.

Lemma 2 (shift). For real s1,…,sis_1, \ldots, s_i and any real cc, softmax(s1+c,…,si+c)=softmax(s1,…,si)\mathrm{softmax}(s_1 + c, \ldots, s_i + c) = \mathrm{softmax}(s_1, \ldots, s_i).

Proof. esj+c/∑lesl+c=ecesj/(ec∑lesl)=esj/∑lesle^{s_j + c} / \sum_l e^{s_l + c} = e^c e^{s_j} / (e^c \sum_l e^{s_l}) = e^{s_j} / \sum_l e^{s_l}. □\square

Theorem 3 (key-only bias). Let a second head use the scores aij+m ja_{ij} + m\,j for j≤ij \le i and the causal mask. Its outputs equal those of ALIBI-HEAD.

Proof. In row ii, aij+mj=(aij−m(i−j))+mia_{ij} + m j = (a_{ij} - m(i - j)) + m i, and mim i is the same for all jj in the row. By Lemma 2 the weights are the same, so the outputs are the same. □\square

Theorem 4 (distance only). The bias b(i,j)=−m(i−j)b(i, j) = -m(i - j) satisfies b(i+t,j+t)=b(i,j)b(i + t, j + t) = b(i, j) for every integer tt. Hence if the queries and keys of positions j,…,ij, \ldots, i are moved to positions j+t,…,i+tj + t, \ldots, i + t and no other key is visible, the outputs are the same.

Proof. (i+t)−(j+t)=i−j(i + t) - (j + t) = i - j. The scores of the moved rows are then the same numbers, and by Lemma 1 so are the outputs. □\square

Theorem 5 (decay). Suppose ∣aij∣≤B|a_{ij}| \le B for all j≤ij \le i. Then the weight of key jj in row ii satisfies pj≤e2B−m(i−j)p_j \le e^{2B - m(i - j)}.

Proof. The denominator of pjp_j is a sum of positive terms that includes the term l=il = i, so it is at least eaii≥e−Be^{a_{ii}} \ge e^{-B}. The numerator is eaij−m(i−j)≤eB−m(i−j)e^{a_{ij} - m(i - j)} \le e^{B - m(i - j)}. Dividing gives pj≤e2B−m(i−j)p_j \le e^{2B - m(i - j)}. ■\blacksquare

With a key-value cache, the queries are at positions pi=i+(M−n)p_i = i + (M - n) among MM keys, and every statement above holds with ii replaced by pip_i. The code computes this case, and for n=Mn = M it is the case above.

References

  1. Press, Smith and Lewis 2022, Abstract and Section 1 (the 1.3B model trained on 1024 tokens, 11% faster and 11% less memory), Figure 1 (extrapolation of sinusoidal, rotary and T5 bias), Section 3 (the biased scores, the slopes, trainable slopes, footnote 10 on the scaling), Section 3 Implementation (the bias in the mask), Section 4 (WikiText-103, books, the 1.3B model)
  2. Vaswani et al. 2017, Section 3.2.1 (scaled dot-product attention), Section 3.5 (the sinusoidal encoding that ALiBi replaces)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/FKDFWV/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples