AI Logic

Positional Encodings

NoPE

Updated:

How NoPE works. The left side shows the flow of an attention layer: no position is added to either the input or the scores, and only the causal mask of an ordinary decoder hides future positions. The upper right shows the attention weights for a length-6 sequence when all keys are identical: the query at position t gives a weight of 1/t to each of the t visible keys, and if only the leading bos contributes a value of 1, the output becomes 1/t, revealing the position. The lower right shows the mean reciprocal rank over 10 tasks on problems longer than in training: absolute position 0.22, RoPE 0.33, ALiBi 0.50, T5 relative position bias 0.55, NoPE 0.69

What Is NoPE

NoPE (No Positional Encoding) refers to a Transformer that injects positional encoding nowhere. No position is added to the input embeddings, and no positional term is added to the attention scores. In 2023, Kazemnejad et al. compared position representations in decoder-only Transformers (language models like GPT that do not look at future words) and showed that NoPE generalizes better to problems longer than those seen in training (NeurIPS 2023).

Without position, it might seem that word order would be lost, but decoders are different. An encoder like BERT, in which every word sees every word, becomes a "bag of words" that cannot distinguish word order without position. A decoder, by contrast, hides future words with a causal mask, so the word at position tt can see only tt words. This "difference in how many words are visible" serves as a positional cue. Earlier work (Haviv et al., 2022, among others) had also reported that decoders without position information can still learn word order.

The paper's new contributions are the following two points.

  • Strongest in length generalization: on 10 tasks such as addition, sorting, and copying, it outperformed sinusoidal positional encoding, RoPE, ALiBi, and the T5 relative position bias on problems longer than in training
  • It can represent both absolute and relative positions: without injected position, the model can in theory learn either representation, and in practice it learned attention close to that of the T5 relative position bias

The left side of the figure at the top of the article shows where position information is injected. It uses the same layout as the figures in the ALiBi, RoPE, and other articles; NoPE injects position nowhere and has only the causal mask of an ordinary decoder. The upper right shows a computation on a length-6 sequence of how this mask alone reveals position (Theorem 1 of the paper). The lower right compares performance on problems longer than in training.

Theory (Learning Position from the Causal Mask Without Injecting It)

The NoPE computation is simply the attention of an ordinary decoder with the positional parts removed. The explanation follows the equations in Appendix B of the paper.

  1. Use only the word embeddings as input. No position embedding is added.
  2. In each layer, compute the scores from the query–key dot product alone (equation below). There is no positional term.
  3. With the causal mask, set the scores of words after the current one to βˆ’βˆž-\infty (as in an ordinary decoder).
  4. Apply softmax to obtain the weights and sum the values.
⟨qt,ki⟩=qt⊀ki(i≀t)\langle q_t, k_i \rangle = q_t^\top k_i \qquad (i \le t)

The paper shows with two theorems why position can be recovered even though it is not injected.

Theorem 1 (absolute position): the first attention layer alone can write each word's position tt into the hidden state. Suppose the input begins with a start token <bos>. If the key weights WKW_K are chosen so that every word has the same key, all scores are equal and the softmax gives a weight of 1/t1/t to each of the tt visible words. If the value weights WVW_V are further chosen to give 1 only for <bos> and 0 otherwise, the output is the following.

ot=βˆ‘i≀t1t vi=1to_t = \sum_{i \le t} \frac{1}{t} \, v_i = \frac{1}{t}

Position 1 gives 1, position 2 gives 0.5, position 3 gives about 0.333, a different value for each position. The subsequent feed-forward layer (a two-layer MLP with ReLU) can recover the position itself from this 1/t1/t. The upper right of the figure at the top of the article shows this construction computed for a length-6 sequence.

Theorem 2 (relative position): once position has been written in the first layer, attention in the second and later layers can express scores split into a content term and a distance term.

⟨qn,km⟩=fcnt(q,k)+frel(nβˆ’m)\langle q_n, k_m \rangle = f_{\mathrm{cnt}}(q, k) + f_{\mathrm{rel}}(n - m)

fcntf_{\mathrm{cnt}} depends only on the content of the words, and frelf_{\mathrm{rel}} depends only on the distance nβˆ’mn - m. In other words, NoPE can build inside the model the "distance-only term" that the T5 relative position bias and ALiBi add from outside.

The theorems show that "such weights exist"; training does not necessarily arrive at them. The paper investigates experimentally which one is chosen when training with SGD, as described in the next section.

Why It Handles Longer Problems Well

Injecting positional encoding seems to give the model more information. The paper discusses, based on experiments, why NoPE nevertheless did better on longer problems.

  • What it learned is relative position: the same input was fed to NoPE and to models with each scheme, and the similarity of attention distributions was measured layer by layer (the average Jensen–Shannon divergence for the closest pair of heads). The closest to NoPE was the T5 relative position bias, and the farthest were absolute position (sinusoidal) and RoPE. This trend held across all layers and all lengths.
  • It looks both near and far: examining how far away the attended words are in the addition task, NoPE and the T5 relative position bias showed distributions with two peaks, "very close" and "far (the problem input)." ALiBi looked mostly nearby because of its distance penalty, and RoPE and absolute position had flat distributions with no preferred distance. Since the two best performers had the same shape, the paper suggests that this two-peaked way of attending suits longer problems.

In schemes that put position values themselves into the input, inputs longer than in training feed the model position values (or rotation angles) it has never seen. NoPE puts in no position values, so at least "unseen position values" do not arise. However, in the paper's experiment with a 1.3B model, NoPE's accuracy also dropped beyond a little under 2x the training length (next section), so NoPE does not fully solve the length problem.

RoPE is often introduced as a relative position scheme, but in this paper's experiments, both its length generalization and its attention distributions behaved like absolute position (sinusoidal).

Experimental Results

Length generalization (Sections 3–4 and Figure 1 of the paper): decoder-only Transformers (12 layers, width 768, 12 heads, about 107M parameters) were trained from scratch for each task, changing only the position representation. For most tasks, models were trained on problems up to length 20 and evaluated by exact-match accuracy on problems up to length 40. On problems of the training length, every scheme was nearly 100% correct.

MethodMean reciprocal rank (10 tasks, higher is better)
Absolute position (sinusoidal)0.22
RoPE0.33
ALiBi0.50
T5 relative position bias0.55
NoPE0.69

The mean reciprocal rank ranks the 5 schemes for each task and condition and averages the reciprocals of the ranks. The 10 tasks are copy and reverse (basic tasks); addition, polynomial evaluation, sorting, summation, parity, and LEGO (math and reasoning); and SCAN and PCFG (standard length generalization datasets), each trained with 3 random seeds. Without any added computation, NoPE matched or beat the T5 relative position bias, the best of the others.

Writing intermediate steps (Section 6): when models were asked to write intermediate computation (a scratchpad, also called chain of thought) before the answer, the only task that improved for every scheme was addition. Results also varied greatly with the scratchpad format, and the paper concludes that "even with a scratchpad, a position representation that generalizes well in length is needed."

Language modeling with a 1.3B model (Appendix F): a 1.3B-parameter model was trained on code data (part of StarCoder, about 30B tokens) with a context length of 1024, and perplexity was measured at various context lengths (lower is better). The table below shows the values on files of 3000–3250 tokens.

Context length1024 (same as training)14001600180020482560
NoPE2.5552.4984.23932.277153.248521.752
ALiBi2.6652.7633.84713.54241.208143.644
RoPE2.506169.800471.389619.115670.209824.417

Up to the training length, the three schemes did not differ much. With contexts longer than in training, RoPE broke down immediately, and NoPE and ALiBi generalized up to about 1800, but beyond that ALiBi was more stable.

Practical Considerations

NoPE works only in decoder-only models with a causal mask. Removing positional encoding from an encoder like BERT (bidirectional attention) yields a "bag of words" model that cannot distinguish word order. In addition, all of the paper's experiments train models from scratch. Simply removing positional encoding from a model pretrained with it does not turn it into NoPE.

Other points to keep in mind:

  • The strong results come from small synthetic tasks: NoPE did best in experiments training models of about 100M parameters separately on tasks such as addition and copying. In language modeling with a 1.3B model, NoPE also degraded beyond a little under 2x the training length, and ALiBi was more stable. The paper also leaves comparison in large-scale pretraining for future work.
  • Perplexity and real tasks are different things: the paper notes that language model perplexity tends to be measured on data with heavy dependence on nearby words, which can make schemes that emphasize nearby words, like ALiBi, look favorable. To compare on tasks that use long contexts, verify on the actual tasks.
  • The first token serves as a cue: in the construction of Theorem 1, the leading <bos> is the reference for counting positions. The paper notes that in practice, an instruction prompt or similar can play the same role.

Comparison with Other Position Representations

MethodWhere position is injectedLearned parametersSequences longer than the training lengthTypical use
Learned positional embeddingAdded to the input embeddings (once)Yes (Lmax⁑×dL_{\max} \times d)Cannot be representedBERT, GPT
Sinusoidal positional encodingAdded to the input embeddings (once)NoneValues can be computed, but accuracy drops sharplyOriginal Transformer
T5 relative position biasA learned scalar per distance bucket added to the scores in each layerYesBest among the explicit schemes on the NoPE paper's synthetic tasksT5, mT5
RoPEQueries and keys in each layer rotated by an angle proportional to positionNoneOnly slightly longerLLaMA, PaLM, and others
ALiBiA distance-proportional penalty subtracted from the scores in each layerNoneTends to keep accuracyWhen using sequences longer than in training
NoPE (this article)Nowhere (position is learned from the causal mask)NoneBest of the 5 schemes on synthetic tasks; up to a little under 2x training length in the 1.3B language modelDecoder-only models
  • When training a decoder-only model from scratch and aiming to improve length generalization without extra computation or parameters, NoPE is a candidate. Implementation just removes the positional encoding, with no additional computation.
  • When using an encoder (bidirectional attention), NoPE cannot be used. Choose a learned positional embedding or a relative position scheme.
  • To keep a large language model stable on inputs longer than in training, ALiBi was more stable over long ranges in the paper's 1.3B experiment. To extend the context of a pretrained RoPE model, there are position interpolation and YaRN.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class NoPEDecoder(nn.Module):
    """Decoder-only Transformer with no positional encoding (Eq. (16) of the paper: <q_t, k_i> = q_t^T k_i)"""

    def __init__(self, vocab: int, d_model: int = 256, n_heads: int = 4, n_layers: int = 4):
        super().__init__()
        self.embed = nn.Embedding(vocab, d_model)          # word embeddings only; no position embedding is created
        layer = nn.TransformerEncoderLayer(d_model, n_heads, 4 * d_model, batch_first=True, norm_first=True)
        self.blocks = nn.TransformerEncoder(layer, n_layers)
        self.head = nn.Linear(d_model, vocab)

    def forward(self, tokens: torch.Tensor) -> torch.Tensor:
        n = tokens.size(1)
        causal = nn.Transformer.generate_square_subsequent_mask(n)   # hide future positions with -inf (this is the positional cue)
        h = self.blocks(self.embed(tokens), mask=causal, is_causal=True)
        return self.head(h)


model = NoPEDecoder(vocab=100).eval()                      # eval() disables dropout for comparison
x = torch.randint(0, 100, (1, 8))
x_long = torch.randint(0, 100, (1, 64))                    # no position table, so inputs of any length go in as is
print(model(x).shape, model(x_long).shape)                 # torch.Size([1, 8, 100]) torch.Size([1, 64, 100])

# Construction of Theorem 1: if all keys are equal, the weights are 1/t each. Summing values that are 1 only for <bos> gives an output of 1/t
T = 6
scores = torch.zeros(T, T)                                  # every key has the same score
scores = scores.masked_fill(torch.triu(torch.ones(T, T, dtype=torch.bool), 1), float("-inf"))
weights = scores.softmax(dim=-1)                            # row t has t entries of 1/t
v = torch.tensor([1.0, 0, 0, 0, 0, 0])                      # 1 only for the first token (<bos>)
print(weights @ v)                                          # tensor([1.0000, 0.5000, 0.3333, 0.2500, 0.2000, 0.1667])

FAQ

Q. How can word order be known without positional encoding?
A.

Because of the decoder's causal mask. The word at position tt can see only tt words, so if, for example, all of them get equal weights, each weight is 1/t1/t, producing a different value for each position. The paper showed that the first attention layer alone can write each word's position into the hidden state (Theorem 1), and that the second and later layers can build a score term that depends only on distance (Theorem 2).

Q. Can it be used in encoders like BERT?
A.

No. In an encoder, every word sees every word, so without positional encoding the model becomes a "bag of words" in which reordering the words does not change each word's output. NoPE works only in decoder-only models with a causal mask, such as GPT.

Q. Is NoPE also the best for large language models?
A.

This is not yet clear. NoPE did best in experiments that trained models of about 100M parameters separately on each synthetic task. In the 1.3B-parameter experiment added in the paper (trained at length 1024), it was about the same as RoPE and ALiBi up to the training length and generalized up to about length 1800, but beyond that ALiBi was more stable. The paper also leaves evaluation in large-scale pretraining for future work.

References

  1. A. Kazemnejad, I. Padhi, K. Natesan Ramamurthy, P. Das, and S. Reddy, "The Impact of Positional Encoding on Length Generalization in Transformers," NeurIPS, 2023.
  2. A. Haviv, O. Ram, O. Press, P. Izsak, and O. Levy, "Transformer Language Models without Positional Encodings Still Learn Positional Information," Findings of EMNLP, 2022.
  3. O. Press, N. A. Smith, and M. Lewis, "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation," ICLR, 2022.