ALiBi (Attention with Linear Biases) is a position encoding method that directly injects a static, non-learned bias into the attention scores of a Transformer model. Unlike sinusoidal or learned absolute position embeddings, ALiBi subtracts a constant penalty from the attention score between a query and key, scaled linearly by their relative distance. This simple mechanism explicitly encodes the inductive bias that tokens closer together are more relevant, without adding any trainable parameters to the model.
Glossary
ALiBi (Attention with Linear Biases)

What is ALiBi (Attention with Linear Biases)?
ALiBi is a position encoding method that biases the attention scores of query-key pairs with a linear penalty proportional to their distance, eliminating the need for learned position embeddings and enabling robust sequence length extrapolation.
The primary advantage of ALiBi is its demonstrated ability to perform context length extrapolation—the model can generalize to input sequences significantly longer than those seen during training with minimal perplexity degradation. By using a fixed linear slope per attention head, ALiBi creates a consistent geometric prior that remains stable at any sequence length, directly addressing the failure modes of other position encoding schemes and reducing the computational overhead associated with learned position representations.
Key Features of ALiBi
Attention with Linear Biases (ALiBi) is a static, non-learned position encoding method that biases query-key attention scores with a linear penalty proportional to their distance. This simple mechanism eliminates the need for learned position embeddings and enables robust sequence length extrapolation.
Linear Distance Penalty
ALiBi subtracts a constant bias from the attention score for each pair of tokens. The penalty increases linearly with the distance between the query and key.
- Formula:
softmax(q_i K^T + m * [-(i-1), ..., -2, -1, 0]) - The slope
mis a head-specific scalar that is geometrically spaced across attention heads. - Closer tokens receive a smaller penalty, naturally encouraging the model to prioritize local context.
- Unlike sinusoidal or learned embeddings, this bias is not added to the word embedding; it is applied directly inside the attention computation.
Zero Learned Parameters
ALiBi requires absolutely no trainable parameters for position encoding. The slopes m are pre-computed constants.
- Slope Calculation: For
nheads, slopes form a geometric sequence starting at2^(-8/n)and ending at2^(-8). - This eliminates the need to train or store a position embedding matrix, reducing model size and complexity.
- The static nature ensures the model's behavior on long sequences is deterministic and not dependent on how far the training data extended.
- This contrasts sharply with Rotary Position Embedding (RoPE) and learned absolute position embeddings, which require careful interpolation for extrapolation.
Robust Sequence Length Extrapolation
ALiBi's primary advantage is the ability to perform inference on sequences far longer than those seen during training without fine-tuning.
- A model trained on 1024 tokens can reliably generalize to 2048, 4096, or even longer sequences.
- The linear bias provides a smooth, monotonic inductive bias that does not break down at unseen lengths.
- This directly addresses the Lost-in-the-Middle problem by providing a consistent structural signal regardless of absolute position.
- Empirical results show ALiBi maintains lower perplexity on extrapolated lengths compared to sinusoidal or RoPE embeddings without any interpolation tricks.
Computational Efficiency
The bias computation is extremely lightweight and can be fused into the attention kernel with negligible overhead.
- The bias mask is a simple Toeplitz matrix that can be pre-computed and cached.
- No additional matrix multiplications or rotations are required, unlike RoPE which applies complex rotations to query and key vectors.
- This makes ALiBi particularly attractive for edge deployment and high-throughput inference scenarios.
- The memory footprint for the bias is
O(sequence_length), which is trivial compared to theO(sequence_length * hidden_dim)KV-Cache.
Causal Mask Integration
For autoregressive decoder models, ALiBi naturally integrates with the causal attention mask to enforce temporal order.
- The linear penalty is applied only to the lower-triangular portion of the attention matrix.
- Future tokens remain masked with
-infwhile past tokens receive the distance-based penalty. - This dual masking ensures the model cannot attend to future information while still prioritizing recent context over distant history.
- The combination creates a strong recency bias that mirrors how many natural language phenomena exhibit local coherence.
Head-Specific Slope Diversity
Each attention head receives a unique slope value, creating a diverse set of receptive fields across the model.
- Shallow slopes (small
m) allow some heads to attend broadly across the entire context. - Steep slopes (large
m) force other heads to focus narrowly on immediate neighbors. - This geometric distribution ensures the model can simultaneously capture both short-range syntax and long-range semantics.
- The diversity is fixed and non-learned, preventing any single head from dominating and ensuring robust generalization.
ALiBi vs. Rotary Position Embedding (RoPE) vs. Learned Positional Embeddings
A technical comparison of three distinct methods for encoding token position information in Transformer attention mechanisms, focusing on their extrapolation behavior, parameter efficiency, and computational overhead.
| Feature | ALiBi | RoPE | Learned Positional Embeddings |
|---|---|---|---|
Encoding Mechanism | Static linear bias added to attention scores pre-softmax | Rotates query and key vectors by position-dependent angles | Adds a learned vector to token embeddings before attention |
Position Type | Relative | Relative (via absolute rotation) | Absolute |
Learnable Parameters | |||
Sequence Length Extrapolation | Strong; zero-shot to 2-3x training length | Strong; with NTK-aware scaling to 4-8x training length | Weak; fails beyond max training length |
Computational Overhead | Negligible; O(1) per attention head | Minimal; O(d) per token for rotation | Negligible; O(1) per token for addition |
Memory Footprint | Zero added parameters | Zero added parameters | Adds max_seq_len × d_model parameters |
Theoretical Basis | Linear decay of attention with distance | Complex-valued rotation in Hilbert space | Empirical; no inductive bias for distance |
Inference on Unseen Lengths | No modification required | Requires frequency scaling intervention | Requires truncation or interpolation |
Frequently Asked Questions
Clear, technical answers to the most common questions about Attention with Linear Biases, its mechanism, and its role in enabling robust sequence length extrapolation for large language models.
ALiBi (Attention with Linear Biases) is a position encoding method that biases the attention scores of query-key pairs with a linear penalty proportional to their distance, eliminating the need for learned position embeddings and enabling robust sequence length extrapolation. Unlike sinusoidal or learned absolute position embeddings, ALiBi does not add positional information to the word embeddings at the bottom of the network. Instead, it subtracts a scalar bias from the attention score computed between a query and key. This bias is a constant multiple of the distance between the two tokens. Specifically, for each attention head, a fixed, non-learned slope m is defined. The bias added is m * (i - j), where i and j are the positions of the query and key tokens, respectively. This simple, additive mechanism penalizes attention scores for tokens that are far apart, creating an inductive bias that favors locality. The slopes are geometrically spaced across heads, allowing different heads to specialize in different distance ranges. Because the bias is relative and linear, the model can generalize to sequence lengths far beyond those seen during training without any modification or interpolation of the position encoding scheme.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
ALiBi is a foundational position encoding method. The following concepts define the surrounding architecture, competing methods, and failure modes that ALiBi was designed to address.
Rotary Position Embedding (RoPE)
The dominant alternative to ALiBi. RoPE encodes position by rotating the query and key vectors in the attention computation, enabling the model to naturally capture relative positional relationships. Unlike ALiBi's static linear penalty, RoPE uses sinusoidal functions to modulate the dot-product attention score based on the relative distance between tokens. This method has become the standard for most state-of-the-art open-source models (Llama, Mistral) due to its strong context length extrapolation properties when combined with NTK-aware scaling.
Context Length Extrapolation
The core problem ALiBi solves. This is the ability of a model to perform inference on sequences longer than those seen during training without catastrophic performance degradation. Standard learned position embeddings fail completely on unseen lengths. ALiBi achieves extrapolation by design: its linear bias penalty is a simple mathematical function of distance, not a learned parameter, so it generalizes to any sequence length without modification. This allows a model trained on 1024 tokens to reliably process 2048+ tokens at inference.
Attention Mechanism
The architectural component ALiBi modifies. In a standard Transformer, the attention score between a query and key is computed as a scaled dot-product. ALiBi intervenes by subtracting a static, non-learned bias from this score before the softmax:
- The bias is proportional to the distance between tokens
- Each attention head gets a unique slope
- Closer tokens receive less penalty; distant tokens receive more This enforces a recency bias that mimics the natural locality found in language.
KV-Cache
The memory buffer that stores pre-computed Key and Value tensors from previous decoding steps to avoid redundant computation during autoregressive generation. ALiBi's simplicity directly benefits KV-Cache management:
- No position-dependent computations in the cache
- The linear bias is applied on-the-fly during attention scoring
- This means cached KV pairs are position-agnostic, simplifying batching and memory allocation Efficient KV-Cache usage is critical for low-latency, high-throughput LLM serving.
Lost-in-the-Middle
A documented failure mode of LLMs where information placed in the center of a long context window is significantly less likely to be retrieved than information at the beginning (primacy bias) or end (recency bias). ALiBi's linear penalty structure inherently reinforces a strong recency bias, which can exacerbate this effect for middle-context tokens. Understanding this trade-off is essential: ALiBi excels at extrapolation but may require careful prompt engineering to ensure critical instructions are placed near the beginning or end of the context window.
FlashAttention
An exact-attention algorithm that dramatically speeds up computation and reduces memory footprint by minimizing HBM reads/writes through tiling and recomputation. ALiBi is fully compatible with FlashAttention because the linear bias can be fused into the attention kernel as a simple element-wise operation. This combination—ALiBi for length extrapolation and FlashAttention for hardware efficiency—enables fast inference on extremely long sequences without the memory overhead of learned position embeddings or complex RoPE calculations.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us