Architecture · Position encoding

ALiBi: Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation

Drop position embeddings and subtract a distance penalty from each attention score, so a language model trained on short sequences still works on longer ones.

ALiBi removes positional vectors from the input of a Transformer and adds a fixed, head-specific linear penalty proportional to the distance between query and key to every dot product before softmax. Training on shorter subsequences cuts compute and GPU memory, while evaluation on much longer sequences stays stable without fine-tuning.

Explaining the paperTrain Short, Test Long: Attention with Linear Biases Enables Input Length ExtrapolationPress, Smith, Lewis · ICLR 2022 · arXiv:2108.12409 ↗

Ofir Press, Noah A. Smith, and Mike Lewis tested four position methods past their training length, replaced position embeddings with one linear ramp inside the causal mask, and then ran an appendix ablation showing that most of the perplexity gain comes from removing chunk boundaries rather than reading distant history.

Every weight matrix inside a Transformer is independent of sequence length. Token embeddings map vocabulary IDs to vectors of width dd, linear projections multiply each vector independently, and self-attention takes dot products between however many queries and keys arrive. Yet a language model trained on 512-token chunks degrades sharply in perplexity (the effective number of equally likely next tokens the model chooses among; lower is better) as soon as inference passes 600 tokens.

This page walks through ALiBi in six parts: why existing position encodings fail past training length, how subtracting a linear distance bias reshapes attention inside one head, how the fixed geometric slope schedule sets head timescales, how to implement the bias with zero extra runtime using softmax shift invariance, what the paper measured up to 1.3 billion parameters, and what Appendix B reveals about why the perplexity curve drops.

Why extrapolation fails in Transformers

In an autoregressive language model, a long document is split into training subsequences of fixed length LL. More context improves next-token predictions, so engineers want large LL at inference time. Training on large LL is expensive because causal self-attention computes an L×LL \times L score matrix in every head and every layer: compute grows as O(L2d)O(L^2 d) and activation memory for the attention maps grows as O(L2)O(L^2).

On the 247M-parameter WikiText-103 Transformer from Baevski and Auli (16 layers, dd = 1024, 8 heads, head width dkd_k = 128, feedforward width dffd_{\text{ff}} = 4096), one attention layer at batch size 1 holds 8 × 512 × 512 ≈ 2.1M scores when LL = 512, and 8 × 3072 × 3072 ≈ 75.5M scores when LL = 3072, 36 times more entries. On a single V100 GPU (Appendix Table 1), training throughput drops from 28.5k words per second at LL = 512 to 26.0k at LL = 1024 and 15.3k at LL = 3072.

Extrapolation means training on shorter sequences of length LL and evaluating on longer sequences of length Lvalid>LL_{\text{valid}} > L without losing quality. Learned absolute position embeddings (used in BERT and GPT-3) cannot extrapolate because their lookup table has no rows beyond index LL. Vaswani et al. (2017, Section 3.5) chose fixed sinusoidal vectors added to the bottom token embeddings partly because the sine and cosine formulas are defined for any index, conjecturing that they might extrapolate past training length.

Press et al. put that conjecture to a controlled test on WikiText-103, holding architecture, seed, and 205 training epochs identical while swapping only the position method. They compare four schemes: sinusoidal embeddings, Rotary Position Embeddings (RoPE) (which rotate queries and keys at every layer), the T5 relative position bias (which adds a learned scalar from 32 logarithmic distance buckets up to distance 128 to each attention logit, shared across layers), and ALiBi.

Figure 1 · Extrapolation cliff on WikiText-103 (Tables 2 & 3)
L_valid2,512

L_valid = 2,512 · ALiBi 18.41 · T5 20.41 · RoPE 31.58 · Sinusoidal 132.41

Switch between L = 512 and L = 1024 training lengths, toggle Zoomed (17-45 PPL, matching Figure 1 of the paper) against Full log scale (up to 500 PPL), and drag L_valid across every measured validation length. T5 Bias hits out-of-memory (OOM) on a 32 GB V100 past 12.5k tokens.

Drag the L_valid slider in Figure 1 from 512 upward. The sinusoidal model trained at L=512L = 512 starts at 20.05 perplexity, dips slightly to 19.91 at 532 to 562 tokens (just 20 to 50 extra tokens), and then climbs steeply: 24.86 at 712 tokens, 43.54 at 1,012, 132.41 at 2,512, and 406.01 at 15,512. Trained at L=1024L = 1024, it improves for only 50 extra tokens before failing the same way. Even though the sinusoidal formula produces valid vectors for position 600, downstream linear layers have only ever seen combinations of positions 1 through 512 and output distorted logits on unseen phase combinations.

RoPE extends the usable margin to roughly 200 extra tokens at L=512L = 512 (19.79 at 712) and 100 extra tokens at L=1024L = 1024 (19.18 at 1,124) before rising to 79.25 and 106.99 at the far end. T5 bias extrapolates much further, improving up to 600 extra tokens at L=512L = 512 (18.77 at 1,112) and 800 extra tokens at L=1024L = 1024 (18.30 at 1,824), because distances beyond 128 all map into one shared clipped bucket. Its weakness is cost: in Fairseq on a V100 GPU, T5 bias trains at 14.4k words/s at L=512L = 512 versus 28.5k for sinusoidal (less than half the speed) and runs out of memory on a 32 GB GPU past 12,512 tokens.

Two architectural properties separate RoPE and T5 bias from sinusoidal embeddings: both inject position inside every attention layer rather than once at the input, and neither adds position information to the value vectors. Press et al. kept those two properties and replaced T5's learned bucket table with a single unlearned line.

How ALiBi works

In standard causal scaled dot-product attention, query qi∈R1×dk\mathbf{q}_i \in \mathbb{R}^{1 \times d_k} at position ii scores keys K≤i∈Ri×dk\mathbf{K}_{\le i} \in \mathbb{R}^{i \times d_k} at positions 1,…,i1, \dots, i, divides by dk\sqrt{d_k}, and normalizes with softmax:

ai=softmax⁡ ⁣(qiK≤i⊤dk)\mathbf{a}_i = \operatorname{softmax}\!\left(\frac{\mathbf{q}_i \mathbf{K}_{\le i}^\top}{\sqrt{d_k}}\right)
(1)

ALiBi deletes positional embeddings from the input layer completely; token representations enter layer 1 as pure word embeddings. Inside every attention head hh, ALiBi adds a static, non-learned linear penalty proportional to the distance between query ii and key jj:

ai(h)=softmax⁡ ⁣(qi(h)K≤i(h)⊤dk+mh⋅[−(i−1),…,−2,−1,0])\mathbf{a}_i^{(h)} = \operatorname{softmax}\!\Big(\frac{\mathbf{q}_i^{(h)} \mathbf{K}_{\le i}^{(h)\top}}{\sqrt{d_k}} + m_h \cdot [-(i-1), \dots, -2, -1, 0]\Big)ai(h)=softmax⁡ ⁣(qi(h)K≤i(h)⊤dk+mh⋅[−(i−1),…,−2,−1,0])\begin{aligned}\mathbf{a}_i^{(h)} = \operatorname{softmax}\!\Big(&\frac{\mathbf{q}_i^{(h)} \mathbf{K}_{\le i}^{(h)\top}}{\sqrt{d_k}} \\ &+ m_h \cdot [-(i-1), \dots, -2, -1, 0]\Big)\end{aligned}
(2)

Writing out a single unmasked entry j≤ij \le i, the pre-softmax logit is:

sij(h)=qi(h)⋅kj(h)dk−mh(i−j)s_{ij}^{(h)} = \frac{\mathbf{q}_i^{(h)} \cdot \mathbf{k}_j^{(h)}}{\sqrt{d_k}} - m_h (i - j)
(3)

Positions j>ij > i receive −∞-\infty from the causal mask as usual, and mh>0m_h > 0 is a fixed positive scalar chosen before training. The bias is added after dividing the dot product by dk\sqrt{d_k}, never before. (Footnote 10 of the paper writes that the bias is not multiplied by the dk\sqrt{d_k} scaling factor; Equation 1 of Vaswani et al. scales by 1/dk1/\sqrt{d_k}, and lines 56 and 225 of the authors' multihead_attention.py confirm q *= head_dim ** -0.5 runs before the dot product and bias addition.) If an implementation added −mh(i−j)-m_h(i-j) before dividing by dk\sqrt{d_k}, every slope at dk=128d_k = 128 would shrink by a factor of 128≈11.3\sqrt{128} \approx 11.3.

Because softmax exponentiates its inputs, subtracting a linear penalty in logit space multiplies every unnormalized attention weight by an exponential decay in distance Δ=i−j\Delta = i - j:

aij(h)∝exp⁡ ⁣(qi(h)⋅kj(h)dk)⋅e−mh(i−j)a_{ij}^{(h)} \propto \exp\!\left(\frac{\mathbf{q}_i^{(h)} \cdot \mathbf{k}_j^{(h)}}{\sqrt{d_k}}\right) \cdot e^{-m_h (i - j)}aij(h)∝exp⁡ ⁣(qi(h)⋅kj(h)dk)⋅e−mh(i−j)\begin{aligned}a_{ij}^{(h)} \propto &\exp\!\left(\frac{\mathbf{q}_i^{(h)} \cdot \mathbf{k}_j^{(h)}}{\sqrt{d_k}}\right) \\ &\cdot e^{-m_h (i - j)}\end{aligned}
(4)

Each step farther into the past cuts a key's relative weight by a constant factor e−mhe^{-m_h}. Think of a megaphone in a corridor: a loud match far down the hall can still beat a quiet neighbor if its dot product exceeds the distance loss, so ALiBi is a soft recency bias rather than a hard sliding-window cutoff.

Work through concrete numbers on a 5-token sequence for the final query t5t_5 (i=5i = 5). Suppose the scaled dot products with keys t1…t5t_1 \dots t_5 are [3.8, 0.9, 1.4, 2.0, 2.2], so t1t_1 has a strong semantic match while t5t_5 has a modest self-match. With no position bias (m=0m = 0), softmax assigns 66% of the weight to t1t_1 and 13% to t5t_5. In ALiBi's steepest 8-head slope m1=0.5m_1 = 0.5, the distance biases are [-2.0, -1.5, -1.0, -0.5, 0.0], shifting the logits to [1.8, -0.6, 0.4, 1.5, 2.2]; weight on t1t_1 drops from 66% to 28% while t5t_5 rises to 42%. In the slowest head m8=1/256≈0.0039m_8 = 1/256 \approx 0.0039, the 4-token penalty is only −0.0156-0.0156, leaving t1t_1 at 66%.

Figure 2 · Inside one head: dot product + linear bias → softmax
slopeh1 · 1/2

head 1: m = 2^-1 (0.50) · row t5: t1 weight 66% → 28%

Drag the slope slider from m = 0 (order-blind edge case) through all eight ALiBi heads (1/256 to 1/2), or click any row t1-t5 to inspect its weights. Toggle Paper vs Code to verify that adding +m·j produces identical softmax weights to -m(i - j).

Why use a linear penalty instead of an exponential or learned curve? In the repository FAQ, Press reports testing exponentially growing penalties and other shapes during development; linear penalties outperformed them. In Section 5, the authors also report that multiplying attention scores by a distance factor (as in the Distance Aware Transformer) degraded language modeling perplexity compared to adding a negative bias.

The geometric slope schedule

A single slope across all heads would force the entire layer into one timescale: a steep slope blinds the model to anything more than a few tokens back, while a flat slope barely distinguishes adjacent words from distant ones. ALiBi assigns each head h∈{1,…,n}h \in \{1, \dots, n\} its own fixed slope from a geometric progression starting at 2−8/n2^{-8/n} with ratio 2−8/n2^{-8/n}:

mh=2−8h/n,h=1,2,…,nm_h = 2^{-8h / n}, \qquad h = 1, 2, \dots, n
(5)

For an 8-head model (the WikiText-103 and BookCorpus architecture), the slopes are 2−1,2−2,…,2−82^{-1}, 2^{-2}, \dots, 2^{-8}, running from 0.50.5 down to 1/256≈0.003911/256 \approx 0.00391 with ratio 1/21/2. For a 16-head model (the 1.3B architecture), ALiBi geometrically interpolates every adjacent pair, producing 2−0.5,2−1,2−1.5,…,2−82^{-0.5}, 2^{-1}, 2^{-1.5}, \dots, 2^{-8} (from 0.70710.7071 down to 0.003910.00391 with ratio 1/21/\sqrt{2}).

Equation (5) has two immediate consequences. First, the slopes cluster near zero: in an 8-head layer, six of the eight heads have mh≤0.125m_h \le 0.125, dedicating most heads to medium and long ranges while reserving one or two for immediate neighbors. Second, for every power-of-two head count (n=8,16,32,64n = 8, 16, 32, 64), the slowest head always ends at the exact same slope mn=2−8=1/256m_n = 2^{-8} = 1/256. Adding heads fills in finer intermediate timescales rather than extending the longest timescale.

From equation (4), head hh reduces an unnormalized weight by a factor of 1/e≈0.3681/e \approx 0.368 every 1/mh1 / m_h tokens. For n=8n = 8, those characteristic decay distances are 2, 4, 8, 16, 32, 64, 128, and 256 tokens. At distance Δ=512\Delta = 512, the slowest head subtracts 512/256=2.0512 / 256 = 2.0 from the logit (weight multiplier e−2≈0.135e^{-2} \approx 0.135). At Δ=2048\Delta = 2048, it subtracts 8.08.0 (multiplier e−8≈3.35×10−4e^{-8} \approx 3.35 \times 10^{-4}). A query-key pair 2,048 tokens apart must beat recent keys by 8 full scaled-logit units just to draw equal attention weight.

Figure 3 · Multi-head exponential decay curves exp(-m_h · Δ)
distance Δ256

slowest head (m = 1/256): penalty -1.00, factor 0.368 · steepest (m = 0.500): factor 2.6e-56

Switch head counts n = 8, 12, 16, 32 and drag token distance Δ from 0 to 2,048. Doubling power-of-two heads interpolates between curves while keeping the slowest head anchored at m = 1/256. At n = 12, amber curves highlight the four extra slopes appended by the official Fairseq code.

The paper states equation (5) for general nn, but all models trained in the paper have a power-of-two head count (8 or 16). In the authors' official repository (fairseq/models/transformer.py, lines 742 to 753), get_slopes(n) uses equation (5) only when log⁡2n\log_2 n is an integer. For any other head count, such as n=12n = 12, the code computes the slopes for the largest power of two below nn (here p=8p = 8, giving 2−1…2−82^{-1} \dots 2^{-8}) and appends the first n−p=4n - p = 4 even-indexed slopes from get_slopes(2 * p), which are 2−0.5,2−1.5,2−2.5,2−3.52^{-0.5}, 2^{-1.5}, 2^{-2.5}, 2^{-3.5}. Toggle n = 12 (code) in Figure 3 to see those four steep amber curves sit beside the eight base curves.

Press et al. found these slopes by testing roughly ten candidate sets on WikiText-103 (Section 3), then reused the exact same formula untouched on Toronto BookCorpus and the 461 GB CC100+RoBERTa corpus. Trainable slopes were tested and rejected because they slowed training by 3% (Footnote 11) and harmed extrapolation.

Zero-overhead code and shift invariance

Standard causal Transformers already construct an L×LL \times L upper-triangular mask containing 00 on and below the diagonal and −∞-\infty above it, then add that mask to the scaled score matrix before softmax. ALiBi replaces that single L×LL \times L mask with a precomputed n×L×Ln \times L \times L tensor whose lower triangle holds −mh(i−j)-m_h(i - j) for each head hh. Because the mask addition already happens in every attention layer, ALiBi introduces zero extra operations and zero trainable parameters.

In fp32, an 8×1024×10248 \times 1024 \times 1024 mask takes 33.6 MB (shared across all 16 layers). In Fairseq's transformer.py (line 763), the authors repeat the mask across the batch dimension to match PyTorch's 3D attn_mask convention, which accounts for the 0 to 100 MB (0 to 0.7%) memory difference reported in Table 1. In modern fused kernels such as FlashAttention, the scalar −mh(i−j)-m_h(i - j) is computed inside registers during the tiled score pass, using zero extra GPU memory.

Line 761 of fairseq/models/transformer.py uses an algebraic shortcut worth knowing if you read the codebase. Instead of building the lower-triangular Toeplitz matrix of distances −(i−j)-(i - j), the code multiplies each slope by a single 1D ramp [0, 1, 2, ..., L-1] and adds that same row vector +mhj+m_h j to every row of the causal mask. Because softmax is invariant to adding any constant cic_i across all entries of row ii, shifting row ii by ci=+mhic_i = +m_h i leaves the probabilities unchanged (where zijz_{ij} is the scaled query-key dot product before adding the bias):

softmax⁡j ⁣(zij+mhj)=softmax⁡j ⁣(zij−mh(i−j))\operatorname{softmax}_j\!\left(z_{ij} + m_h j\right) = \operatorname{softmax}_j\!\left(z_{ij} - m_h (i - j)\right)softmax⁡j ⁣(zij+mhj)=softmax⁡j ⁣(zij−mh(i−j))\begin{aligned}&\operatorname{softmax}_j\!\left(z_{ij} + m_h j\right) \\ &= \operatorname{softmax}_j\!\left(z_{ij} - m_h (i - j)\right)\end{aligned}
(6)

Verify equation (6) directly in Figure 2 by toggling Paper: -m(i - j) and Code: +m·j: every entry of the bias matrix changes, while every bar in the softmax chart stays frozen. In half precision (fp16), the +mhj+m_h j shortcut loses precision: at L=32,768L = 32{,}768 and m1=0.5m_1 = 0.5, m1jm_1 j reaches +16,384+16{,}384, where fp16 spacing degrades to 16.0 and washes out small dot-product differences before softmax subtracts the row max. Computing the relative distance j−i≤0j - i \le 0 keeps nearby biases near zero at any sequence length.

During autoregressive generation with a KV cache, decoding step tt produces a single query qt\mathbf{q}_t of shape (B, n, 1, d_k) against cached keys of shape (B, n, t, d_k). The bias for that row is the 1D vector m_h * [-(t-1), ..., -1, 0], so previously cached keys and values stay untouched as tt grows past LL.

# ALiBi causal mask and attention for one layer (PyTorch-style)
import math, torch

def get_slopes(n):                               # fairseq transformer.py:742-753
    def power_of_2(k):
        start = 2.0 ** (-(2.0 ** -(math.log2(k) - 3)))   # equals 2^(-8/k)
        return [start * (start ** i) for i in range(k)]
    if math.log2(n).is_integer():
        return power_of_2(n)
    p = 2 ** math.floor(math.log2(n))            # workaround for non-2^a heads
    return power_of_2(p) + get_slopes(2 * p)[0::2][: n - p]

def build_alibi_mask(n_heads, seq_len, device):
    slopes = torch.tensor(get_slopes(n_heads), device=device)     # (n,)
    pos = torch.arange(seq_len, device=device)                    # (L,)
    dist = pos.unsqueeze(0) - pos.unsqueeze(1)                    # j - i <= 0
    causal = torch.triu(torch.full((seq_len, seq_len), float("-inf"),
                                   device=device), diagonal=1)
    # shape (n, L, L): 0 on diagonal, -m*(i-j) below, -inf above
    return slopes[:, None, None] * dist[None, :, :] + causal[None, :, :]

# In each attention layer: no position embeddings added to token vectors x.
# q, k, v have shape (B, n_heads, L, d_k). Gradients flow to W_q, W_k, W_v, W_o
# only; alibi_mask is a fixed buffer with requires_grad=False.
scores = (q @ k.transpose(-2, -1)) * (d_k ** -0.5)   # scale BEFORE adding bias
weights = torch.softmax(scores + alibi_mask, dim=-1) # (B, n, L, L)
out = weights @ v                                    # values carry no position

What the paper measured

Press et al. evaluated ALiBi across three corpora of increasing scale: WikiText-103 (103M tokens, 247M-parameter model, 8 heads), Toronto BookCorpus (700M tokens, 247M-parameter model, 8 heads, reusing the WikiText-103 slopes with no retuning), and CC100+RoBERTa (461 GB of web text, news, books, and Wikipedia; 1.3B-parameter model with 25 layers, 16 heads, d=2048d = 2048, dff=8192d_{\text{ff}} = 8192, trained for 50,000 updates on 128 V100 GPUs).

On WikiText-103 without extrapolation (Lvalid=LL_{\text{valid}} = L, Table 5), ALiBi outperforms the sinusoidal baseline at every sequence length from 512 up to 3,072: at L=3072L = 3072, ALiBi reaches 17.60 validation perplexity (18.30 test, Table 6) compared to sinusoidal's 18.67±0.2418.67 \pm 0.24 (19.38 test), RoPE's 18.57 (19.28 test), and T5 bias's 18.01 (18.73 test). With sliding-window evaluation (stride S=512S = 512, stepping overlapping windows by 512 tokens; Table 7), the L=3072L = 3072 ALiBi model reaches 17.66 test perplexity, ahead of Transformer-XL (18.3) and Shortformer (18.15).

With extrapolation on WikiText-103, an ALiBi model trained on just L=512L = 512 tokens starts at 19.73 validation perplexity at Lvalid=512L_{\text{valid}} = 512 and drops to 18.40 when evaluated at Lvalid=3072L_{\text{valid}} = 3072 (19.08 test). That beats the L=3072L = 3072 sinusoidal model (18.67 valid, 19.38 test) while training at 28.3k words/s versus 15.3k words/s (1.84x faster as reported in Section 4.1). Even trained on L=512L = 512 and stretched to Lvalid=15,512L_{\text{valid}} = 15{,}512 (30x longer), perplexity holds at 18.31. On Toronto BookCorpus (Tables 8 and 9), the same pattern repeats with untouched slopes: ALiBi trained on L=512L = 512 and evaluated at 3,072 scores 13.55 valid (10.98 test), beating the L=3072L = 3072 sinusoidal baseline at 14.46 valid (11.67 test).

Figure 4 · Training speed, compute, and perplexity frontier (Tables 1, 5, 11, 12)
modelALiBi L=512

ALiBi trained on L=512 → eval 3072 · PPL 18.40 · 28.3k WPS · 15.3 GB · 1.84x faster than Sin L=3072 (Sec. 4.1), beats it by 0.27 PPL

Switch between WikiText-103 (247M, eval 3072) and CC100+RoBERTa (1.3B, eval 2048). Click any point or drag the slider to compare speed, GPU-hours, memory, and perplexity. On the 1.3B plot, notice both Sinusoidal L = 2048 runs: equal wall-clock time (44.2k updates, Table 11) and equal update count (50k updates, Table 12).

At the 1.3B scale on 461 GB of text, two behaviors change relative to WikiText-103. First, when Lvalid=LL_{\text{valid}} = L (no extrapolation, Table 12), ALiBi's accuracy edge over sinusoidal vanishes: at 50k updates, ALiBi versus sinusoidal is 9.79 vs 9.71 (L=512L = 512), 9.16 vs 9.15 (L=1024L = 1024), and 8.84 vs 8.83 (L=2048L = 2048). The authors suggest that ALiBi's recency prior acts as an extra regularizer on smaller datasets like WikiText-103, while massive data washes out the in-distribution gap.

Second, the 1.3B extrapolation advantage depends on whether you match wall-clock time or update count. In Table 11 (matching 5.9k GPU-hours on 128 V100s, evaluated at Lvalid=2048L_{\text{valid}} = 2048), ALiBi trained on L=1024L = 1024 finishes all 50.0k updates using 26.2 GB per GPU and scores 8.92 perplexity, while the L=2048L = 2048 sinusoidal baseline uses 29.3 GB (3.1 GB or 11.8% more memory), completes only 44.2k updates in the same time, and scores 9.01. Across five evenly spaced training checkpoints, ALiBi reaches a target perplexity 11% faster. If you let the L=2048L = 2048 sinusoidal model keep running for another 0.8k GPU-hours to reach 50.0k updates (6.7k total hours, Table 12), it finishes at 8.83, 0.09 better than ALiBi trained at L=1024L = 1024. On this large corpus, ALiBi's best extrapolated perplexity peaks near 2L2L (9.30 at 1,012 for L=512L = 512, rising slightly to 9.54 at 2,048; 8.90 at 2,024 for L=1024L = 1024) and stays stable out to 10,000 tokens. Section 4.2 offers a hypothesis for the 2L2L peak: at length 2L2L, half of all predicted positions still have context lengths ≤L\le L seen during training, whereas past 2L2L more than half lie past LL. The sinusoidal baseline degrades immediately at L+1L + 1, hitting 48.85 at Lvalid=2048L_{\text{valid}} = 2048 when trained at L=1024L = 1024.

Why ALiBi works: the early token curse

Seeing an ALiBi model trained on 512 tokens drop from 19.73 perplexity at Lvalid=512L_{\text{valid}} = 512 to 18.40 at Lvalid=3072L_{\text{valid}} = 3072 invites a natural assumption: the model must be spotting long-range patterns 2,000 or 3,000 tokens apart. In Appendix B, Press et al. run a controlled sliding-window experiment that points to a different mechanism.

Non-overlapping evaluation slices a validation corpus into independent chunks of length LvalidL_{\text{valid}}. Every time you make a cut, the tokens immediately after the cut lose their left context: position 1 has zero preceding tokens, position 2 has one, and the first 100 tokens of every chunk have 100 or fewer tokens of history. Press et al. (2021) named this penalty the early token curse. On a 3,072-token article split into six chunks of 512, 600 tokens (19.5%) sit within 100 tokens of a chunk boundary. Run the same article as one chunk of 3,072, and only the first 100 tokens (3.3%) suffer that boundary loss.

Two competing hypotheses therefore explain a falling non-overlapping perplexity curve as LvalidL_{\text{valid}} grows past LL:

  1. Longer effective context: the model actively retrieves useful information from tokens more than LL steps back.
  2. Fewer chunk boundaries: the model still relies mainly on the most recent LL tokens, and simply stays stable as chunks grow so fewer tokens fall victim to the early token curse.

To separate the two, Appendix B.2 re-evaluates the exact same L=512L = 512 and L=1024L = 1024 WikiText-103 models using a sliding window with stride 1 (S=1S = 1): each forward pass advances by one token and predicts only the final token, giving every prediction after the document start a full LvalidL_{\text{valid}} tokens of history. That eliminates the early token curse at high inference cost: scoring a 3,072-token document at Lvalid=512L_{\text{valid}} = 512 requires 2,561 forward passes instead of 6.

Figure 5 · Appendix B test: early token curse vs stride-1 sliding window
L_valid512

non-overlap PPL 19.73 · sliding S=1 PPL 17.98 · gap 1.75 · starved tokens 19.5%

Toggle Non-overlapping vs Sliding window (S = 1) and drag L_valid from 512 to 3,072. Top: amber bars mark tokens with 100 or fewer tokens of context in a 3,072-token document. Bottom: WikiText-103 L_train = 512 validation perplexity under non-overlapping evaluation (Table 5) versus stride-1 sliding window (Table 15).

Compare the two curves in Figure 5. Under stride-1 sliding-window evaluation (Table 15), the L=512L = 512 ALiBi model scores 17.98 at Lvalid=512L_{\text{valid}} = 512, 17.92 at 1,024, 18.20 at 1,536, 18.28 at 2,048, and 18.30 at 3,072. The L=1024L = 1024 ALiBi model moves from 17.46 at 1,024 to 17.92 at 3,072. Perplexity does not improve with longer windows once the early token curse is removed; it stays flat and drifts up by 0.3 to 0.5 points. Under the same stride-1 test, the sinusoidal model still explodes from 18.35 to 204.42 at 1,024 and 360.12 at 3,072 (Table 13), and T5 bias degrades from 17.92 to 30.77 (Table 14).

Equation (4) explains why ALiBi behaves this way. Because every head applies an exponential decay e−mhΔe^{-m_h \Delta} with mh≥1/256m_h \ge 1/256, tokens far beyond the training window are smoothly driven toward zero weight instead of injecting out-of-distribution position embeddings into the dot products. ALiBi gives a single fast non-overlapping pass most of the accuracy of an expensive sliding window, because every token in a long chunk sees a clean local window of recent history without hitting an artificial cut.

Effective context limits and later adoption

Because ALiBi required only a few lines of mask code and added zero inference overhead, several prominent early open-weight language models adopted it, including BigScience's BLOOM (176B parameters, trained at L=2048L = 2048) and MosaicML's MPT-7B and MPT-30B (where MPT-7B-StoryWriter fine-tuned to 65k tokens and ran at 84k).

Subsequent receptive-field analysis (Chi et al., ACL 2023) quantified the built-in trade-off that Appendix B already hinted at. Every ALiBi head has a finite effective window determined by its slope mhm_h. Even with 16 or 25 stacked layers, no single head stays global across tens of thousands of tokens: at distance 10,000, the slowest slope 1/2561/256 imposes a logit penalty of −39.1-39.1 (weight factor 10−1710^{-17}). For next-token language modeling perplexity, which depends heavily on the last few hundred tokens, that soft locality keeps perplexity low and stable. For exact long-range retrieval tasks such as finding a passkey or variable definition buried 30,000 tokens earlier, a fixed linear decay suppresses the distant key's attention weight toward zero.

Later long-context models (Llama 2, Llama 3, Mistral, Qwen) converged on RoPE paired with frequency-rescaling methods (Position Interpolation, NTK-aware scaling, and YaRN) plus short long-context fine-tuning. Those methods lack ALiBi's zero-shot stability out of the box, but once fine-tuned they keep distant keys reachable without an exponential distance tax.

Provenance Verified against primary literatureHow we verify
Press, Smith & Lewis (2021 / ICLR 2022)Primary source (arXiv:2108.12409v2): extrapolation benchmarks (Section 2, Tables 1-4), ALiBi definition and geometric slope schedule (Section 3, Footnotes 9-11), WikiText-103, Toronto BookCorpus, and 1.3B CC100+RoBERTa results (Section 4, Tables 5-12), and the Appendix B early token curse diagnosis (Tables 13-15).
ofirpress/attention_with_linear_biasesOfficial Fairseq repository: get_slopes(n) with the non-power-of-2 fallback and the shift-invariant 1D bias construction (fairseq/models/transformer.py, lines 742-763 and 1003-1017), input position embedding removal (line 941), and 1/sqrt(d_k) query scaling before mask addition (fairseq/modules/multihead_attention.py, lines 56 and 225).
Vaswani et al. (2017), Section 3.5Sinusoidal positional encodings and the original conjecture that sinusoidal functions might allow Transformers to extrapolate to sequence lengths longer than those seen during training.
Su et al. (2021); Raffel et al. (2020)RoPE (rotary position embeddings) and T5 relative position bias (32 learned buckets per head shared across layers, logarithmic spacing up to max distance 128), both evaluated in Section 2 of the ALiBi paper.
Baevski & Auli (2018); Press et al. (2021)The 247M Adaptive Inputs Transformer LM used as the WikiText-103 baseline (16 layers, d = 1024, 8 heads, d_ff = 4096) and Shortformer, which defined the early token curse and staged training.
Scao et al. (2022); Chi et al. (ACL 2023)Post-paper adoption in BLOOM (176B) and receptive-field analysis showing that ALiBi heads behave like local windows whose effective reach is bounded by the slowest slope.
correctionTwo paper-versus-code discrepancies and one comparison nuance were verified directly against arXiv:2108.12409v2 and the official Fairseq repository. First, Footnote 10 states that "The ALiBi bias is not multiplied by the sqrt(d_k) scaling factor from Equation 1 of Vaswani et al. (2017)"; Vaswani et al. divide by sqrt(d_k) (multiply by 1/sqrt(d_k)), and fairseq/modules/multihead_attention.py (lines 56, 225) scales queries by head_dim**-0.5 before computing dot products and adding the ALiBi mask, so the bias is added after 1/sqrt(d_k) scaling. Second, Section 3 states that for any n heads the slopes are the geometric sequence starting at 2^(-8/n) with ratio 2^(-8/n), whereas fairseq/models/transformer.py (lines 742-753) applies that formula only when n is a power of 2 and otherwise appends even-indexed slopes from the next power of 2. Third, the abstract and Section 4.2 report that the 1.3B ALiBi model (L = 1024) matches or beats Sinusoidal (L = 2048) while training 11% faster; Table 11 makes that comparison at equal wall-clock time (5.9k GPU-hours, halting Sinusoidal at 44.2k updates: 8.92 vs 9.01 PPL), whereas Table 12 runs both to 50k updates and records 8.92 (ALiBi L = 1024, 5.9k h) against 8.83 (Sinusoidal L = 2048, 6.7k h) and 8.84 (ALiBi L = 2048, 6.7k h).

Questions you might still have

?

If ALiBi removes position embeddings altogether, how does the model know word order?
Every attention head subtracts m_h * (i - j) from the dot product between query i and key j, and the causal mask forbids attending to j > i. Because different heads apply different slopes (from 0.5 down to 1/256), a token receives a weighted sum of recent values in steep heads and broader values in shallow heads. Across stacked layers, those relative offsets are enough to recover both relative distance and, near the start of a sequence, approximate absolute position via the causal boundary.

?

Why did trainable slopes perform worse than fixed slopes?
Press et al. report in Section 3 (and Footnote 11) that making the slopes learnable slowed training by 3% and degraded length extrapolation. When gradients can adjust m_h freely during training on sequences of length L, heads can shrink slopes toward zero or specialize them to the exact training span L, losing the uniform recency decay that keeps longer sequences in distribution at test time.

?

Does ALiBi really let a 512-token model read 10,000 tokens of context?
No. Appendix B.2 (Table 15) tests the L = 512 ALiBi model with a stride-1 sliding window so every prediction already has full context, and perplexity stays flat or edges slightly up from 17.98 at L_valid = 512 to 18.30 at L_valid = 3072. Even the slowest head has slope 1/256, which applies a -8.0 logit penalty (weight multiplier 0.00034) at distance 2048. What ALiBi actually gives you at 10,000 tokens is stability without chunk boundaries, avoiding the early token curse at non-overlapping speed.

?

How do you adapt ALiBi for a bidirectional encoder like BERT?
In a causal decoder, i - j is always nonnegative for unmasked keys. For a bidirectional encoder, keys can lie on either side of query i, so the distance penalty uses the absolute distance -m_h * |i - j| (symmetric around the diagonal), or separate forward and backward slopes across half the heads each. The official ALiBi repository links to both bidirectional variants in its issue tracker.

?

Does ALiBi work with FlashAttention?
Yes. Because ALiBi is a deterministic scalar function of head index h and indices (i, j), fused kernels such as FlashAttention compute -m_h * (i - j) on the fly inside the inner tiling loop without ever allocating the n-by-L-by-L bias matrix in GPU memory. The FlashAttention explainer covers how tiled attention avoids materializing the full L-by-L score matrix.

?

Why did later open models like Llama switch from ALiBi to RoPE?
Early open models such as BLOOM (176B) and MPT (7B, 30B) adopted ALiBi for zero-shot stability past their 2,048-token training window. Once long-context tasks demanded retrieving a specific fact buried 32,000 or 128,000 tokens back, ALiBi ran into its own exponential decay ceiling: its slowest head still penalizes distance at rate 1/256. RoPE combined with Position Interpolation, NTK-aware scaling, or YaRN (covered in the RoPE explainer) lets models fine-tune to 128k tokens without hard-suppressing distant keys.

References & further reading

  1. Ofir Press, Noah A. Smith, Mike Lewis (2022). Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation. ICLR 2022 (arXiv:2108.12409v2). Official code: github.com/ofirpress/attention_with_linear_biases.
  2. Ashish Vaswani et al. (2017). Attention Is All You Need. NeurIPS 2017 (arXiv:1706.03762). Section 3.5 introduces sinusoidal position encodings and their extrapolation conjecture.
  3. Jianlin Su et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv:2104.09864.
  4. Colin Raffel et al. (2020). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer (T5). JMLR 2020 (arXiv:1910.10683). Section 2.1 defines the 32-bucket relative position bias.
  5. Ofir Press, Noah A. Smith, Mike Lewis (2021). Shortformer: Better Language Modeling using Shorter Inputs. ACL 2021. Defines the early token curse and compares sliding-window versus non-overlapping evaluation.
  6. Alexei Baevski, Michael Auli (2018). Adaptive Input Representations for Neural Language Modeling. ICLR 2019. Source of the 247M WikiText-103 Transformer baseline.
  7. Zihang Dai et al. (2019). Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context. ACL 2019 (arXiv:1901.02860).
  8. Ta-Chung Chi, Ting-Han Fan, Alexander I. Rudnicky, Peter J. Ramadge (2023). Dissecting Transformer Length Extrapolation via the Lens of Receptive Field Analysis. ACL 2023. Analyzes ALiBi's finite per-head receptive field.
  9. Teven Le Scao et al. (2022). BLOOM: A 176B-Parameter Open-Access Multilingual Language Model. arXiv:2211.05100. Large-scale deployment of ALiBi.