The Impact of Positional Encoding on Length Generalization in Transformers (NoPE)

POSITION ENCODING LENGTH GENERALIZATION Kazemnejad et al. · 2023
arXiv:2305.19466

上一代的问题:Explicit position encoding (APE, Sinusoidal, T5 Relative, ALiBi, RoPE) was considered necessary for Transformer models — all prior work assumed that without explicit positional signals, the self-attention mechanism is inherently permutation-invariant and cannot distinguish token order. Length generalization was studied only through perplexity, never through systematic downstream task evaluations.

这代改了什么:This work theoretically proves that a decoder-only Transformer with causal masking can recover absolute positions in its first layer and implement relative position encoding in subsequent layers — all without any explicit positional encoding (NoPE). The theoretical proof is accompanied by a comprehensive empirical evaluation across 10 diverse tasks.

效果:NoPE achieves the best mean reciprocal rank across 10 tasks, outperforming T5 Relative, ALiBi, Rotary, and APE on length generalization — while requiring zero additional computation (no extra attention terms, no position embedding lookup). This result provided theoretical justification for position-free architectures like Mamba.

一、核心背景

1.1 Length Generalization Problem

Length generalization refers to the ability of a sequence model to perform reliably on input sequences longer than those seen during training. This is a critical capability for real-world deployment: training on long sequences is expensive due to the quadratic O(n2) complexity of self-attention, so there is strong practical incentive to train on shorter sequences and extrapolate to longer ones at inference time.

The problem is fundamentally about distribution shift between training and inference: the model never observes certain patterns (e.g., long-range dependencies, large positional differences) during training, yet must handle them at test time. This is especially challenging for Transformers because:

1.2 The Role of Position Encoding

Position encoding (PE) is the mechanism by which Transformers incorporate sequence order information. Without PE, the dot-product attention between query and key vectors is permutation-invariant: shuffling the input tokens produces the same attention distribution. Since natural language is inherently sequential, this invariance is a fundamental limitation.

Over the years, a rich taxonomy of position encodings emerged:

CategoryExamplesCore Idea
Absolute PESinusoidal (Vaswani et al.), Learned APEAdd a position-specific vector to each token embedding; positions are fixed indices
Relative PET5 Relative Bias, Shaw et al.Add a bias term to attention logits based on offset (n - m) between positions
Rotary (RoPE)Su et al.Rotate query/key vectors by an angle proportional to position; relative distance naturally emerges
ALiBiPress et al.Add a linear bias proportional to distance to attention scores; no learned parameters

1.3 Prior Evaluation Gap

A critical limitation of prior work was the evaluation methodology: position encoding methods were almost exclusively evaluated using perplexity on language modeling benchmarks. Perplexity is an aggregate metric that does not isolate length generalization ability. A model could have good perplexity while failing catastrophically on specific algorithmic tasks requiring precise position tracking (e.g., copying the last token to the first position).

This paper fills that gap by evaluating across 10 diverse tasks that explicitly test the model's ability to reason about position and structure at longer sequence lengths.

二、实验设置

2.1 Model Architecture

The experiments use a decoder-only GPT-style Transformer with approximately 107M parameters — large enough to exhibit meaningful behavior but small enough for systematic ablation. Key architectural details:

The architecture is deliberately minimal: no layer normalization modifications, no special initialization schemes, no auxiliary losses. This ensures that any observed differences in length generalization can be attributed to the position encoding method alone.

2.2 Task Suite (10 Tasks)

The evaluation spans tasks of increasing complexity, testing both simple pattern matching and complex algorithmic reasoning:

TaskTypeDescriptionTarget
CopyMemoryCopy input sequence verbatimSymbolic
ReverseMemoryReverse input sequence orderSymbolic
AdditionArithmeticAdd two numbers digit by digitNumerical
Polynomial EvaluationMathEvaluate a polynomial at given pointNumerical
SortingAlgorithmicSort a list of integersSymbolic
SummationArithmeticSum a list of numbersNumerical
ParityBooleanCompute parity of a binary stringBoolean
LEGOCompositionalCompositional instruction followingSymbolic
SCANCompositionalCommand to action sequence mappingSymbolic
PCFGStructureProbabilistic context-free grammar parsingStructural

2.3 Training and Evaluation Protocol

The evaluation follows a rigorous protocol designed to isolate length generalization:

Why MRR? MRR is more robust than raw accuracy because it accounts for the relative ordering of methods across diverse task difficulties. A method that consistently ranks 2nd across all tasks is preferred over one that ranks 1st on easy tasks but last on hard ones.

三、核心发现

3.1 NoPE Outperforms All Explicit PEs

The central empirical result is striking: the model with no explicit position encoding (NoPE) achieves the best mean reciprocal rank across all 10 tasks, outperforming every hand-designed position encoding method.

Overall ranking: NoPE > T5 Relative > ALiBi > Rotary > APE

This ranking is consistent across most individual tasks. On tasks that require precise position information (Copy, Reverse), NoPE's advantage is particularly pronounced because the causal mask provides a natural inductive bias for ordering. On tasks that require compositional generalization (LEGO, SCAN), the gap narrows but NoPE still leads.

Critically, NoPE achieves this performance with zero additional computation: there are no extra bias terms in attention, no position embedding lookup tables, no rotation operations. The model simply uses the raw token embeddings and relies on the causal mask to infer position.

3.2 Theoretical Proof: NoPE Can Represent Positions

The paper provides two theorems that establish the theoretical foundations for why NoPE works. These are the most intellectually significant contributions of the paper.

Theorem 1: Absolute Encoding in the First Layer

The first theorem states that a single-layer decoder-only Transformer with causal masking can recover absolute positions in its hidden states. Formally:

H^(1) contains information about positions [1, 2, ..., T+1] in the hidden representation after the first layer
Theorem 1: First-layer absolute position encoding

Proof intuition: The causal mask creates an asymmetric attention pattern: token i can only attend to tokens [1, ..., i]. As a result, the first token has only itself to attend to, the second token attends to itself and the first, and so on. The softmax attention naturally encodes the cardinality of the prefix — how many tokens precede a given position — which is exactly the absolute position. Specifically:

The model can learn to read this entropy signal from the attention output and encode it in the hidden state. This is possible because the causal mask introduces a strict ordering that breaks the permutation invariance of standard self-attention.

Theorem 2: Relative Encoding in Subsequent Layers

The second theorem extends the result to deeper networks. Given that the first layer encodes absolute positions, subsequent layers can implement relative position encoding by computing dot products between position-aware hidden states:

⟨qn, km⟩ = fcontent(q,c) + frelative(n - m)
Theorem 2: Relative position encoding emerges in deeper layers

Proof intuition: Once the first layer produces hidden states H(1) that contain both content information (what token is at position i) and position information (i itself), subsequent self-attention layers can compute dot products that decompose into:

The key insight is that the causal mask's structure allows the model to factorize these two information sources. The relative position term f_relative(n - m) emerges naturally from the interaction between position-encoded hidden states, without any explicit relative position bias.

Moreover, SGD can choose between absolute and relative strategies depending on which is more useful for the task. This flexibility is a significant advantage over hand-designed PEs that force a specific positional inductive bias.

3.3 Empirical: NoPE Approximates T5 Relative Bias

The theoretical claim that NoPE implements implicit relative position encoding is supported by attention pattern analysis. The paper measures the similarity between attention patterns learned by NoPE and those produced by each explicit PE method, using Jensen-Shannon divergence (JSD):

PE Method ComparedJSD to NoPE AttentionInterpretation
T5 Relative BiasLowestNoPE attention patterns most similar to T5 Relative
ALiBiMediumModerate similarity
RoPE (Rotary)HighDistinct attention patterns
APE (Learned Absolute)HighestLeast similar to NoPE

This empirical result validates Theorem 2: NoPE's internal representations are functionally equivalent to those produced by relative position encoding. The attention distributions are nearly indistinguishable from T5 Relative Bias, suggesting that the model discovers the same position-dependent attention patterns without any explicit supervision or architectural bias.

Why this matters: The fact that SGD naturally discovers relative position encoding strategies when no explicit PE is provided suggests that relative position information is the optimal inductive bias for causal language modeling. The causal mask provides just enough signal for the optimization to find this solution.

四、Scratchpad (Chain-of-Thought) 分析

4.1 Scratchpad Effects on Length Generalization

An important auxiliary finding concerns the role of scratchpad (chain-of-thought) reasoning in length generalization. The paper finds that scratchpad is not universally helpful — its utility depends on both the task and the position encoding method.

Key finding: Scratchpad (CoT) improves length generalization only for the Addition task, and this holds across all PE methods. For other tasks (Sorting, Polynomial Evaluation, Parity), scratchpad either has no effect or slightly hurts performance.

4.2 Format Sensitivity

When scratchpad does help, the specific format of the scratchpad is highly impactful. The paper ablates several scratchpad components:

Scratchpad ComponentDescriptionImpact on Performance
Input representationHow the problem is formattedCritical — determines whether positional information is preserved
Computation stepsIntermediate arithmetic or logic stepsHelpful for Addition; harmful for tasks with single-step answers
Output formatHow the answer is structuredLess sensitive than input representation
Variable trackingStoring intermediate variable assignmentsHelpful for complex tasks but adds token overhead
Remaining operationsTracking what is left to computeSubtle effect — can introduce interference for simple tasks

The input representation format is the most sensitive component: a small change in how the input is tokenized or delimited can cause a large swing in length generalization performance. For instance, using explicit positional markers (e.g., "x_1 = 5, x_2 = 3") versus implicit ordering affects generalization by up to 30%.

4.3 Implications for CoT Research

This finding has broader implications for the chain-of-thought reasoning literature. It suggests that:

五、理论分析深度解析

5.1 Why Causal Mask Encodes Position

The central theoretical insight is that a causal mask is itself a position encoding mechanism. To understand why, consider how softmax attention operates under a causal mask:

For token at position n, the attention distribution is computed over tokens [1, ..., n]. The softmax normalizes this prefix of varying length:

An,m = exp(qn * km) / Σj=1n exp(qn * kj)
Causal masked attention — the normalization denominator is a function of position n

The normalization denominator grows with n: for n=1, it sums over 1 term; for n=2, over 2 terms; for n=T, over T terms. This means the scale of the attention output is position-dependent. The model can use this scale signal to infer absolute position.

More formally, consider the extreme case where all attention scores are equal (q * k = 0 for all pairs). Then:

An,m = 1/n for all m <= n
Uniform attention distribution — the position signal is directly visible in the attention entropy

The entropy of this uniform distribution is log(n), which depends only on position n, not on content. A linear layer following attention can learn to decode this signal into a position encoding.

5.2 Relative Position from Absolute Encodings

Once the first layer produces hidden states that encode both content and absolute position, subsequent layers can implement relative position encoding through a simple mechanism. Consider two hidden states:

The dot product hn * hm can be decomposed as:

hn * hm = [cn + pn] * [cm + pm] = cn * cm + cn * pm + pn * cm + pn * pm
Dot product decomposition into content and position terms

The last term pn * pm depends only on the absolute positions, not on the content. If the position encoding pn is a function that maps position indices to vectors (e.g., sinusoidal or learned), then pn * pm = f(n, m). Under common choices (sinusoidal, rotary), this reduces to f(n - m) — a function of the relative offset.

Thus, the model can learn to separate content and position subspaces in its hidden representations via SGD, without any architectural modifications. The position subspace encodes absolute positions in early layers and relative positions in deeper layers.

5.3 Comparison with Explicit PEs

Why do explicit position encodings harm rather than help length generalization? The paper provides several hypotheses:

PE MethodWhy It Hurts Length Generalization
APE (Learned)Learned embeddings are optimized for training lengths; at test time, positions > L have random initializations, producing out-of-distribution signals
SinusoidalFixed frequencies may not extrapolate; the periodic structure can create confusing aliasing at longer distances
RoPERotation frequencies are fixed; at large position differences, the angle wraps or becomes indistinguishable from other offsets
ALiBiLinear bias assumes a fixed distance scale; may not generalize to much longer sequences where the bias slope is inappropriate
T5 RelativeLog-binned relative positions; the bin boundaries are set during training and may not suit longer sequences

In contrast, NoPE's position signal scales naturally with sequence length because it is derived from the causal mask's prefix-counting property. The signal (attention entropy/scale) at position n depends on n itself, not on a predefined set of embeddings or frequencies.

Core insight: NoPE's length generalization advantage stems from the fact that its position signal is emergent rather than imposed. The model learns to use the causal mask's natural position signal, which scales gracefully with sequence length rather than breaking at unseen positions.

六、上下游关联

6.1 Previous Work

This paper stands on the shoulders of extensive position encoding research:

The key gap in all prior work: no one asked whether explicit PE is necessary at all. The assumption was so deeply embedded that it became an unquestioned architectural axiom.

6.2 Impact and Next Work

The NoPE finding had profound implications for subsequent architecture design:

6.3 Adoption in Practice

ArchitecturePosition MethodInfluence of NoPE
Mamba (SSM)None (NoPE + no attention)Direct: provided theoretical justification
Griffin (Hybrid SSM-Attention)NoPE for SSM, RoPE for attentionPartial: SSM branch follows NoPE
LLaMA 1/2/3RoPEIndirect: later models reduced RoPE frequency count
GPT-4 / ClaudeUndisclosed (likely RoPE variant)Indirect: NoPE showed that simpler positional methods are viable

七、个人思考

7.1 Counterintuitive Result: Explicit PE Harms Extrapolation

The finding that adding more information (explicit position signals) worsens length generalization is deeply counterintuitive. Normally, providing the model with more relevant features should improve performance. Why does this fail here?

The key is distribution shift: explicit PEs are optimized for the training distribution (positions 1-20) and produce unreliable signals outside it. NoPE avoids this because its position signal — the prefix-counting property of causal masking — is definitionally consistent at any length. The model is not learning a mapping from position indices to vectors; it is learning to decode a naturally occurring signal that scales with sequence length.

7.2 The Causal Mask as a Position Encoding Mechanism

The deepest insight of this paper is that the causal mask encodes position by construction. Every autoregressive Transformer already has a built-in position encoding mechanism — the limited receptive field created by the mask. This means that the entire literature on explicit position encodings may have been solving a problem that did not exist (or at least, that the architecture had already solved).

This is reminiscent of the Layer Normalization placement debate (Pre-LN vs Post-LN): a simple, already-present architectural feature was overlooked for years, and once understood, simplified the entire design.

7.3 Simplified Architecture: One Less Hyperparameter

From an engineering perspective, NoPE offers a compelling simplicity argument:

7.4 Broader Lesson: Questioning Deeply Held Assumptions

NoPE's greatest contribution may be methodological: it demonstrates the value of questioning foundational assumptions in deep learning research. The belief that Transformers need explicit position encoding was so widely held that no one had systematically tested it. The paper's disciplined approach — combining theoretical proof, diverse task evaluation, and careful ablation — provides a model for how to challenge such assumptions.

This is a recurring pattern in ML history:

The pattern suggests that as architectures evolve, the emergent properties of the design (like causal masking's position encoding) gradually subsume what were once considered essential hand-designed components.

7.5 Connections to the Broader Transformer Story

In the narrative arc of Transformer research, NoPE occupies a pivotal position:

The paper thus marks a transition point between the PE-centric era and the post-attention era. Its theoretical framework — proving that causal masking provides position information — laid the groundwork for architectures that dispense with both attention and explicit position encoding entirely.