NeurIPS 2026Coming to NeurIPS?Explore papers, orals & directions

Contextual Position Encoding: Learning to Count What's Important

Olga Golovneva, Tianlu Wang, Jason Weston, Sainbayar Sukhbaatar

TL;DR

Transformers traditionally measure sequence positions by blindly counting raw tokens, making it difficult for them to reason about higher-level abstract units like words or sentences. Contextual Position Encoding (CoPE) solves this by dynamically calculating positions based on context, allowing the model to increment position counts only on specific, meaningful tokens. This simple shift allows models to effortlessly generalize to abstract structures, drastically improving performance on counting tasks, long-context scenarios, and language modeling.

What Problem Does This Paper Address?

The attention mechanism in Transformers is inherently order-invariant, treating sequences as unordered sets. To fix this, models use Position Encoding (PE)—such as Absolute PE or Rotary Position Embedding (RoPE)—to inject sequence order. However, virtually all existing PE methods use tokens as their fundamental unit of measurement.

This token-centric approach introduces a major flaw: tokens are highly variable. Depending on the tokenizer, a single word can be split into one or many tokens, and a sentence can span anywhere from ten to hundreds of tokens. If a model needs to attend to "the previous sentence" or "the third word back," standard PE methods struggle because the token-distance is highly unpredictable. This architectural limitation causes even state-of-the-art Large Language Models (LLMs) like GPT-4 and Llama-2 to fail at trivial tasks, such as counting how many times a specific word appears in a given sentence.

Methods

CoPE addresses this by integrating position addressing directly with context addressing. Instead of blindly incrementing the position counter for every token, CoPE uses a soft gating mechanism to decide which tokens are worth counting.

Figure 1: Contextual Position Encoding (CoPE). Standard position encoding methods such as Relative PE are based on token positions. In contrast, CoPE computes gate values conditioned on the context first, then uses that to assign positions to tokens using a cumulative sum. This allows positions to be contextualized, and represent the count of different units like words, verbs or sentences. CoPE operates on each attention head and so can attend to different position types on each. In this example, attending to the last sentence using Relative PE is challenging, and the best it can do is a decaying attention (“recency bias”). CoPE can count the sentence endings and simply attend to position “0”.

For a given query token $i$ and key token $j$, CoPE computes a gate value $g_{ij}$ using a sigmoid function: $$g_{ij} = \sigma(q_i^\top k_j)$$

The relative position $p_{ij}$ is then calculated as the cumulative sum of these gate values between the current token and the target token: $$p_{ij} = \sum_{k=j}^i gik$$

Because these gate values are fractional (between 0 and 1), the resulting position $p_{ij}$ can also be a fraction. To map these fractional positions to vectors, CoPE linearly interpolates between the two closest integer position embeddings.

Crucially, because CoPE operates independently on each attention head, different heads can learn to track different abstractions simultaneously. For example, one head can turn its gates "on" only for punctuation tokens to count sentences, while another head can activate its gates only for the first token of a word to count words.

Datasets

The authors evaluated CoPE across a mix of synthetic reasoning tasks and real-world language modeling datasets:

  • Toy Tasks: The Flip-Flop task (testing long-range robust memory retrieval), Selective Copy (copying specific tokens while ignoring blank filler tokens), and an algorithmic Counting task.
  • Language Modeling: The standard Wikitext-103 dataset (100M tokens from Wikipedia).
  • Code Modeling: A custom 20M-parameter Transformer trained on a mix of code data to evaluate structured text performance.

Key Insights and Ideas

  • Context-Dependent Distance: Position and context addressing should not be separate operations. By allowing the context to dictate the position metric, the model can dynamically adjust its "yardstick" depending on what it is reading.
  • Length Generalization via Sparsity: Because the model only increments positions on relevant tokens, the maximum position value ($p_{max}$) can be kept small. Even if a test sequence is thousands of tokens long, if it only contains 20 sentences, a model capped at 64 positions can easily process it without running out of position embeddings.
  • Emergent Structural Awareness: When trained on natural text, attention heads naturally learn to isolate structural boundaries. As shown in the paper's attention maps, certain heads automatically learn to focus exclusively on paragraph breaks or section headers.
Figure 4: CoPE can focus attention on abstract elements like current paragraph (left) and section (right). Here we show attention induced by position alone on Wikitext-103. Since CoPE is contextualized, it can attend to paragraphs and sections by their position. On the left, the segments are found to be separated by newline tokens (indicated by black plus signs), while the right is separated by section titles like “= = Description = =” (similarly marked).

Key Results

  • Perfect Out-of-Distribution (OOD) Generalization: On the Flip-Flop, Selective Copy, and Counting tasks, CoPE achieved a 0.0% error rate in-distribution and maintained near-perfect accuracy out-of-distribution, completely outclassing RoPE and Absolute PE, which failed dramatically when sequence lengths increased.
  • Data Efficiency: On the counting task, CoPE converged to near-zero error with a fraction of the training data required by standard relative PE methods.
Figure 2: CoPE outperforms relative PE on the counting task, especially with less training data of the task.
  • Perplexity Improvements: On Wikitext-103, CoPE achieved a test perplexity of 23.46, outperforming Relative PE (23.81). On the code modeling task, CoPE achieved a test perplexity of 3.9, beating RoPE (4.1).
  • Superior Context Scaling: When trained on a context length of 512 or 1024 and evaluated on sequences up to 2500 tokens, CoPE maintained stable, low perplexity, whereas standard Relative PE performance degraded rapidly.
Perplexity stability of CoPE when evaluating on longer context lengths than seen during training.

Limitations and Future Work

While promising, the authors note a few limitations:

  • Scale: The experiments were conducted on relatively small models (up to 124M parameters). Whether these advantages hold or become even more pronounced at the scale of billions of parameters remains to be tested.
  • Compute Overhead: Calculating the gate values adds an extra layer of query-key interactions. While the authors proposed optimizations (like reusing the attention matrix multiplication), it still introduces minor computational complexity compared to static PEs like RoPE.
  • Broader Modalities: The paper focuses entirely on text and code, but the authors suggest that context-dependent position encoding could be highly beneficial for video and speech processing, where uniform token-counting is even less intuitive.

Summary updated

BibTeX
@misc{golovneva2024contextual,
  author = {Olga Golovneva and Tianlu Wang and Jason Weston and Sainbayar Sukhbaatar},
  title = {{Contextual Position Encoding: Learning to Count What's Important}},
  year = {2024},
  eprint = {2405.18719},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2405.18719},
}
Figure