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 ExtrapolationOfir 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 , 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 . More context improves next-token predictions, so engineers want large at inference time. Training on large is expensive because causal self-attention computes an score matrix in every head and every layer: compute grows as and activation memory for the attention maps grows as .
On the 247M-parameter WikiText-103 Transformer from Baevski and Auli (16 layers, = 1024, 8 heads, head width = 128, feedforward width = 4096), one attention layer at batch size 1 holds 8 × 512 × 512 ≈ 2.1M scores when = 512, and 8 × 3072 × 3072 ≈ 75.5M scores when = 3072, 36 times more entries. On a single V100 GPU (Appendix Table 1), training throughput drops from 28.5k words per second at = 512 to 26.0k at = 1024 and 15.3k at = 3072.
Extrapolation means training on shorter sequences of length and evaluating on longer sequences of length without losing quality. Learned absolute position embeddings (used in BERT and GPT-3) cannot extrapolate because their lookup table has no rows beyond index . 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.
L_valid = 2,512 · ALiBi 18.41 · T5 20.41 · RoPE 31.58 · Sinusoidal 132.41
Drag the L_valid slider in Figure 1 from 512 upward. The sinusoidal model trained at 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 , 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 (19.79 at 712) and 100 extra tokens at (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 (18.77 at 1,112) and 800 extra tokens at (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 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 at position scores keys at positions , divides by , and normalizes with softmax:
ALiBi deletes positional embeddings from the input layer completely; token representations enter layer 1 as pure word embeddings. Inside every attention head , ALiBi adds a static, non-learned linear penalty proportional to the distance between query and key :
Writing out a single unmasked entry , the pre-softmax logit is:
Positions receive from the causal mask as usual, and is a fixed positive scalar chosen before training. The bias is added after dividing the dot product by , never before. (Footnote 10 of the paper writes that the bias is not multiplied by the scaling factor; Equation 1 of Vaswani et al. scales by , 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 before dividing by , every slope at would shrink by a factor of .
Because softmax exponentiates its inputs, subtracting a linear penalty in logit space multiplies every unnormalized attention weight by an exponential decay in distance :
Each step farther into the past cuts a key's relative weight by a constant factor . 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 (). Suppose the scaled dot products with keys are [3.8, 0.9, 1.4, 2.0, 2.2], so has a strong semantic match while has a modest self-match. With no position bias (), softmax assigns 66% of the weight to and 13% to . In ALiBi's steepest 8-head slope , 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 drops from 66% to 28% while rises to 42%. In the slowest head , the 4-token penalty is only , leaving at 66%.
head 1: m = 2^-1 (0.50) · row t5: t1 weight 66% → 28%
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 its own fixed slope from a geometric progression starting at with ratio :
For an 8-head model (the WikiText-103 and BookCorpus architecture), the slopes are , running from down to with ratio . For a 16-head model (the 1.3B architecture), ALiBi geometrically interpolates every adjacent pair, producing (from down to with ratio ).
Equation (5) has two immediate consequences. First, the slopes cluster near zero: in an 8-head layer, six of the eight heads have , dedicating most heads to medium and long ranges while reserving one or two for immediate neighbors. Second, for every power-of-two head count (), the slowest head always ends at the exact same slope . Adding heads fills in finer intermediate timescales rather than extending the longest timescale.
From equation (4), head reduces an unnormalized weight by a factor of every tokens. For , those characteristic decay distances are 2, 4, 8, 16, 32, 64, 128, and 256 tokens. At distance , the slowest head subtracts from the logit (weight multiplier ). At , it subtracts (multiplier ). A query-key pair 2,048 tokens apart must beat recent keys by 8 full scaled-logit units just to draw equal attention weight.
slowest head (m = 1/256): penalty -1.00, factor 0.368 · steepest (m = 0.500): factor 2.6e-56
The paper states equation (5) for general , 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 is an integer. For any other head count, such as , the code computes the slopes for the largest power of two below (here , giving ) and appends the first even-indexed slopes from get_slopes(2 * p), which are . 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 upper-triangular mask containing on and below the diagonal and above it, then add that mask to the scaled score matrix before softmax. ALiBi replaces that single mask with a precomputed tensor whose lower triangle holds for each head . Because the mask addition already happens in every attention layer, ALiBi introduces zero extra operations and zero trainable parameters.
In fp32, an 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 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 , the code multiplies each slope by a single 1D ramp [0, 1, 2, ..., L-1] and adds that same row vector to every row of the causal mask. Because softmax is invariant to adding any constant across all entries of row , shifting row by leaves the probabilities unchanged (where is the scaled query-key dot product before adding the bias):
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 shortcut loses precision: at and , reaches , where fp16 spacing degrades to 16.0 and washes out small dot-product differences before softmax subtracts the row max. Computing the relative distance keeps nearby biases near zero at any sequence length.
During autoregressive generation with a KV cache, decoding step produces a single query 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 grows past .
# 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 positionWhat 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, , , trained for 50,000 updates on 128 V100 GPUs).
On WikiText-103 without extrapolation (, Table 5), ALiBi outperforms the sinusoidal baseline at every sequence length from 512 up to 3,072: at , ALiBi reaches 17.60 validation perplexity (18.30 test, Table 6) compared to sinusoidal's (19.38 test), RoPE's 18.57 (19.28 test), and T5 bias's 18.01 (18.73 test). With sliding-window evaluation (stride , stepping overlapping windows by 512 tokens; Table 7), the 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 tokens starts at 19.73 validation perplexity at and drops to 18.40 when evaluated at (19.08 test). That beats the 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 and stretched to (30x longer), perplexity holds at 18.31. On Toronto BookCorpus (Tables 8 and 9), the same pattern repeats with untouched slopes: ALiBi trained on and evaluated at 3,072 scores 13.55 valid (10.98 test), beating the sinusoidal baseline at 14.46 valid (11.67 test).
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
At the 1.3B scale on 461 GB of text, two behaviors change relative to WikiText-103. First, when (no extrapolation, Table 12), ALiBi's accuracy edge over sinusoidal vanishes: at 50k updates, ALiBi versus sinusoidal is 9.79 vs 9.71 (), 9.16 vs 9.15 (), and 8.84 vs 8.83 (). 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 ), ALiBi trained on finishes all 50.0k updates using 26.2 GB per GPU and scores 8.92 perplexity, while the 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 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 . On this large corpus, ALiBi's best extrapolated perplexity peaks near (9.30 at 1,012 for , rising slightly to 9.54 at 2,048; 8.90 at 2,024 for ) and stays stable out to 10,000 tokens. Section 4.2 offers a hypothesis for the peak: at length , half of all predicted positions still have context lengths seen during training, whereas past more than half lie past . The sinusoidal baseline degrades immediately at , hitting 48.85 at when trained at .
Why ALiBi works: the early token curse
Seeing an ALiBi model trained on 512 tokens drop from 19.73 perplexity at to 18.40 at 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 . 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 grows past :
- Longer effective context: the model actively retrieves useful information from tokens more than steps back.
- Fewer chunk boundaries: the model still relies mainly on the most recent 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 and WikiText-103 models using a sliding window with stride 1 (): each forward pass advances by one token and predicts only the final token, giving every prediction after the document start a full tokens of history. That eliminates the early token curse at high inference cost: scoring a 3,072-token document at requires 2,561 forward passes instead of 6.
non-overlap PPL 19.73 · sliding S=1 PPL 17.98 · gap 1.75 · starved tokens 19.5%
Compare the two curves in Figure 5. Under stride-1 sliding-window evaluation (Table 15), the ALiBi model scores 17.98 at , 17.92 at 1,024, 18.20 at 1,536, 18.28 at 2,048, and 18.30 at 3,072. The 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 with , 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 ) 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 . 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 imposes a logit penalty of (weight factor ). 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.
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
- 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.
- 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.
- Jianlin Su et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv:2104.09864.
- 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.
- 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.
- Alexei Baevski, Michael Auli (2018). Adaptive Input Representations for Neural Language Modeling. ICLR 2019. Source of the 247M WikiText-103 Transformer baseline.
- Zihang Dai et al. (2019). Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context. ACL 2019 (arXiv:1901.02860).
- 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.
- Teven Le Scao et al. (2022). BLOOM: A 176B-Parameter Open-Access Multilingual Language Model. arXiv:2211.05100. Large-scale deployment of ALiBi.
How could this explainer be improved? Found an error, or something unclear? I read every message.