Contextual Position Encoding: Learning to Count What's Important
Olga Golovneva, Tianlu Wang, Jason Weston, Sainbayar Sukhbaatar
TL;DR
Contextual Position Encoding (CoPE) introduces context-dependent position encoding for Transformers, enabling positions to be conditioned on surrounding context rather than solely by token indices. By computing gates that select which prior tokens to count and interpolating fractional positions, CoPE supports multi-unit addressing (e.g., words, sentences) and improves generalization to longer contexts. Across toy tasks and language/code modeling, CoPE outperforms traditional absolute/relative PE and demonstrates robust in-distribution and out-of-distribution performance, along with insightful attention patterns. The work highlights a practical, scalable approach to richer position signaling that can benefit long-range reasoning in diverse domains.
Abstract
The attention mechanism is a critical component of Large Language Models (LLMs) that allows tokens in a sequence to interact with each other, but is order-invariant. Incorporating position encoding (PE) makes it possible to address by position, such as attending to the i-th token. However, current PE methods use token counts to derive position, and thus cannot generalize to higher levels of abstraction, such as attending to the i-th sentence. In this paper, we propose a new position encoding method, Contextual Position Encoding (CoPE), that allows positions to be conditioned on context by incrementing position only on certain tokens determined by the model. This allows more general position addressing such as attending to the $i$-th particular word, noun, or sentence. We show that CoPE can solve the selective copy, counting and Flip-Flop tasks where popular position embeddings fail, and improves perplexity on language modeling and coding tasks.
