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

Contextual Position Encoding: Learning to Count What’s Important

Olga Golovneva, Tianlu Wang, Jason E Weston, Sainbayar Sukhbaatar · Submission to ICLR 2025 · Rejected

TL;DR

Current Large Language Models (LLMs) measure sequence position strictly by token counts, making it difficult to attend to higher-level semantic structures like the $i$-th sentence, word, or paragraph. Contextual Position Encoding (CoPE) solves this by dynamically conditioning position increments on sequence content via data-dependent gating. By learning what to count, CoPE enables robust abstraction, resolves long-standing attention glitches on algorithmic tasks, and delivers consistent perplexity and accuracy gains across language and code modeling.

What Problem Does This Paper Address?

Standard Transformer attention is permutation-invariant, requiring explicit position encodings (PE)—such as sinusoidal embeddings, learnable absolute vectors, or Rotary Position Embeddings (RoPE). However, virtually all popular PE schemes treat raw tokens as the fundamental unit of distance.

This token-centric worldview has significant shortcomings:

  • Token granularity is arbitrary: Due to Byte-Pair Encoding (BPE), a single word can span one or multiple tokens, while a sentence can vary from ten to hundreds of tokens.
  • Context-blind position extraction: Standard PE cannot easily execute queries like "attend to the last sentence" or "retrieve the last occurrence of token $X$," because token counts fluctuate between occurrences. In fact, powerful models like GPT-4 and Llama-3.1-70B frequently fail at simple tasks requiring counting words within the "last sentence."

The authors argue that position addressing and context addressing should not be separate mechanisms; position itself must adapt to the context.

Methods

CoPE introduces a mechanism where positions advance only when contextually relevant tokens appear:

  1. Context-Dependent Gating: For every query $q_i$ and key $k_j$ ($j < i$), CoPE computes a gating value: $$g_{ij} = \sigma(q_i^\top k_j)$$ A gate value near $1$ indicates that token $j$ should increment the distance metric (e.g., a punctuation mark denoting a sentence boundary), while $0$ means it is ignored (e.g., filler or padding).

  2. Contextual Position Accumulation: The relative position of token $j$ with respect to current token $i$ is calculated via a cumulative sum: $$p_{ij} = \sum_{k=j}^i g_{ik}$$ If all gates are $1$, CoPE naturally falls back to standard relative PE ($p_{ij} = i - j + 1$).

  3. Continuous Embedding Interpolation: Because $p_{ij}$ can take fractional values, CoPE interpolates between learnable integer position embeddings $e[p]$: $$e[p_{ij}] = (p_{ij} - \lfloor p_{ij} \rfloor)e[\lceil p_{ij} \rceil] + (1 - p_{ij} + \lfloor p_{ij} \rfloor)e[\lfloor p_{ij} \rfloor]$$ Computationally, the dot products $q_i^\top e[p]$ are evaluated first up to a bounded maximum position $p_{\max} \ll T$, making interpolation an efficient scalar operation.

  4. Multi-Head Independence: Different attention heads can compute distinct gate patterns independently—for instance, one head can track raw tokens, another words, and another paragraphs or section dividers.

Datasets

The authors evaluated CoPE across algorithmic benchmarks, natural language, and code:

  • Synthetic Benchmarks:
  • Flip-Flop Task: Recalling the most recent bit conditioned on alternating write, ignore, and read instructions.
  • Selective Copying: Copying a sequence while ignoring variable-length blank tokens.
  • Symbolic Counting: Tracking and printing variable values after multiple reset, increment, and dummy pass operations.
  • Novel Benchmark — WORDCOUNT and WORDCOUNT-HARD: Built from the TinyStories dataset, testing an LLM’s ability to count occurrences of a specific target word in the last $k$ sentences. In WORDCOUNT-HARD, three stories are concatenated to expand context size threefold.
  • Language & Code Modeling:
  • Wikitext-103 (100M tokens) for language modeling and context length extrapolation.
  • A Code dataset (100B tokens, 20M-parameter model) following the Llama-2 training distribution.
  • 1T-token pre-training of a 1.4B parameter model, evaluated on standard zero/few-shot downstream benchmarks (BoolQ, PIQA, SIQA, HellaSwag, WinoGrande, ARC-e/c, OpenBookQA, MMLU) as well as Wikipedia and C4 validation sets.

Key Insights and Ideas

  • Counting What Matters: When inspecting the learned attention maps, CoPE heads spontaneously specialize: certain heads place gating weights almost exclusively on newline tokens (counting paragraphs) or Markdown section headers (counting sections).
  • Out-of-Distribution (OOD) Extrapolation: In tasks like Selective Copy and Flip-Flop, relative PE degrades when sequences grow longer because distances shift. CoPE ignores irrelevant noise/blank tokens, allowing it to generalize to unseen sequence lengths without performance drops.
  • Minimal Parameter Footprint: CoPE does not need to be present at every layer. Placing CoPE in just 4 of 24 layers (every 6th layer) with $p_{\max} = 64$ added only 0.04% parameters while maintaining competitive throughput.

Key Results

  • Synthetic Tasks:
  • On the Selective Copy task, CoPE achieved 0.0% error on in-domain, dense OOD, and sparse OOD sets, whereas RoPE completely failed (40.1% in-domain, 100% OOD error).
  • On the Flip-Flop task, CoPE achieved 0.0% in-distribution and 4.9% OOD error (vs. RoPE’s 1.8% and 20.3%).
  • WORDCOUNT-HARD: Fine-tuning a 1.4B model with CoPE + RoPE yielded 77.7% accuracy (0.18 NLL) versus 66.9% (0.24 NLL) for RoPE alone. (For perspective, zero-shot Llama-3.1-70B scores only 3.4%).
  • Language and Code Perplexity:
  • On Wikitext-103, CoPE reached 23.46 test PPL (vs. 23.81 for Relative PE and 24.87 for Absolute PE). When combined with Relative PE, it reached 23.23.
  • On Code modeling, CoPE improved perplexity by 17% over Absolute PE and 5% over RoPE (3.9 vs. 4.1 test PPL).
  • 1.4B Pre-Training at Scale: CoPE achieved ~3% better validation perplexity on Wikipedia and C4, reaching the baseline RoPE model's 1T-token performance 40% faster (0.6T vs. 1.0T tokens), while improving average accuracy across 9 downstream benchmarks by 1.0%.

Limitations and Future Work

  • Scale: Experiments were limited to models up to 1.4B parameters; validating scaling behavior on 7B–70B+ regimes remains open.
  • Initial Training Dynamics: The authors noted that CoPE initially lags behind standard embeddings in the first ~10% of training tokens before overtaking them once gating stabilizes.
  • Beyond Text and Code: The authors highlight audio and video as high-potential frontiers, where fixed token/frame position is even less aligned with underlying semantic events than in text.

Summary updated

BibTeX
@misc{golovneva2024contextual,
  author = {Olga Golovneva and Tianlu Wang and Jason E 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