AI Logic

Positional Encodings

Learned Positional Embedding

Updated:

How a learned positional embedding is used. The left side shows the flow up to the attention layers: the positional embedding is added to the token embedding before entering the N attention layers (position information is added only once, at the input). The right side shows the positional embedding table, with one vector row per position from 0 to 511; for a 5-word sentence, the rows for positions 0–4 are looked up and added to the token embeddings. Positions 512 and beyond have no row in the table and cannot be represented

What Is a Learned Positional Embedding

A learned positional embedding prepares one vector for each position ("1st," "2nd," ...), learns its values during training, and adds it to the word embedding. Just as words are looked up in an embedding table, positions are looked up in a table too.

Position information is needed because scaled dot-product attention, the core of the Transformer, does not distinguish word order. Attention only computes a weight for each pair of words, so on its own it treats "the dog chases the cat" and "the cat chases the dog" as the same bag of words.

This method was used by Gehring et al. in 2017 in a convolutional translation model (ConvS2S), and the Transformer paper of the same year used it in a comparison with sinusoidal positional encoding. Since then, many representative models such as BERT, GPT, and ViT have adopted it.

The figure at the top of the article shows where the position information is injected. The left side is the flow up to the attention layers: the positional embedding is added only once, at the input. The right side is the positional embedding table, from which as many rows as the sentence length are looked up starting from the top. The articles on relative position representations, RoPE, and ALiBi use figures with the same layout, so the injection points can be compared side by side.

Theory (Building the Table and Adding It)

The explanation follows the notation of the ConvS2S paper (Section 3.1). Let Lmax⁑L_{\max} be the maximum length that can be handled and dd the embedding size.

  1. Prepare a positional embedding table PP. It is a matrix whose rows are positions and whose columns are dimensions, of size Lmax⁑×dL_{\max} \times d. Its values are randomly initialized like any other weights.
  2. Look up the jj-th input word xjx_j in the word embedding table to get a vector wjw_j.
  3. Look up row pjp_j for position jj in table PP and add it to wjw_j. This becomes the model input eje_j.
  4. During training, the gradient of the loss also flows into pjp_j, and the values of table PP are updated together with the word embeddings.

The addition in step 3 can be written as follows.

ej=wj+pj,pj=P[j]∈Rd,0≀j<Lmax⁑e_j = w_j + p_j, \qquad p_j = P[j] \in \mathbb{R}^{d}, \qquad 0 \le j < L_{\max}

Because the two are added, the length of pjp_j is set to dd, the same as the word embedding. In ConvS2S, positional embeddings are likewise added to the words the decoder has output so far.

BERT additionally adds an embedding indicating "sentence A or sentence B" (the segment embedding) and uses the sum of the three as input (Figure 2 of the BERT paper). The GPT paper also writes the input as "token embedding matrix WeW_e + position embedding matrix WpW_p."

In PyTorch, a positional embedding can be built with the same nn.Embedding as word embeddings. Simply feed position indices 0,1,2,…0, 1, 2, \dots instead of word indices. The only difference from sinusoidal positional encoding is whether the table values are set by a formula or learned.

Why Training Alone Can Represent Position

Each row of the table starts out as random numbers. It still works as position information because a word at the same position always gets the same vector added, whatever the sentence. During training, the model learns to tell apart "the vector added at position 0" and "the vector added at position 1," and adjusts the table values so that those differences can be used when computing attention weights.

As an analogy, think of a seating chart in a classroom where seats never change. The seat numbers themselves mean nothing, but if the same number is attached to the same seat every day, the teacher can learn "the student in front" and "the student next to them." Which number belongs to which arrangement is learned through use.

In practice, learned positional embeddings end up with similar vectors for nearby positions. The ViT paper examined the cosine similarity between the positional embeddings of image patches and showed that nearby patches are more similar, and that patches in the same row or column are also similar (Figure 7 of the ViT paper). Without being told about rows or columns, the model learned the two-dimensional layout of the image from training alone.

However, training only determines the rows for positions that actually appear during training. Positions not in the table (Lmax⁑L_{\max} and beyond), and even rows for positions that rarely appear in training, are not learned well. This is the most important caveat in practice.

Experimental Results

Comparison with sinusoidal (Transformer paper, row (E) of Table 3): on the English→German translation development set (newstest2013), replacing sinusoidal positional encoding with learned positional embeddings gave almost the same perplexity and BLEU.

Position representationPerplexity (lower is better)BLEU
Sinusoidal (base model)4.9225.8
Learned positional embedding4.9225.7

Noting that the two gave nearly identical results, the paper chose sinusoidal because it may allow values to be computed for sequences longer than those seen in training.

Removing positional embeddings (ConvS2S paper, Table 4): on English→German translation (WMT'14, newstest2014), the positional embeddings on the encoder side (source) and decoder side (target) were removed and compared.

SettingValidation perplexityBLEU
ConvS2S (both)6.6421.7
Remove source positional embeddings6.6921.3
Remove target positional embeddings6.6321.5
Remove both6.6821.2

Even removing both lowered BLEU by only 0.5. The paper explains that within the range visible to the convolutions (27 words in the encoder, 25 in the decoder), the model can learn relative positions on its own. In a Transformer, which does not use convolutions, word order cannot be distinguished at all without position information, so positional embeddings matter much more.

Comparison on images (ViT paper, Table 8): the 5-shot linear evaluation accuracy on ImageNet is compared for ViT-B/16.

Position representationAccuracy
No positional embedding0.61382
1D learned positional embedding (patches in raster order)0.64206
2D learned positional embedding (row and column embeddings concatenated)0.64001
Relative positional embedding0.64032

Adding position information raises accuracy by about 3 points, but the differences between methods are small. For this reason, ViT uses the simplest option, a 1D learned positional embedding.

Practical Considerations

A learned positional embedding cannot handle inputs longer than the number of table rows Lmax⁑L_{\max}, because vectors for positions Lmax⁑L_{\max} and beyond simply do not exist. In BERT, Lmax⁑=512L_{\max} = 512, so longer documents must be split or truncated. The ALiBi paper (Press et al., 2022) also points out that this method has no way to represent positions beyond Lmax⁑L_{\max} and cannot extrapolate to sequences longer than in training.

Other points to keep in mind:

  • Later positions tend to be undertrained: if the training data contains few long sequences, the rows for later positions are rarely updated. To reduce computation, BERT runs 90% of pre-training steps on sequences of length 128 and the remaining 10% on length 512 so that the later positional embeddings get learned (Appendix A.2 of the BERT paper).
  • Rebuild the table when changing the input length: in ViT, raising the image resolution for fine-tuning increases the number of patches, and the pretrained positional embeddings no longer fit as is. The ViT paper interpolates the positional embeddings in 2D according to their location in the original image.
  • Parameters increase: the table has size Lmax⁑×dL_{\max} \times d. For example, with Lmax⁑=512L_{\max} = 512 and d=768d = 768, it has about 390,000 parameters. This is small relative to the whole model, but it grows as Lmax⁑L_{\max} increases.

The positional embedding is added only once, to the model's first input. Position information reaches the upper layers through residual connections. This is where it differs from relative position representations, RoPE, and ALiBi, which re-inject position in every attention layer.

Comparison with Other Position Representations

Position representations are easiest to compare by "where position is injected," "whether it is learned," and "whether it handles sequences longer than in training."

MethodWhere position is injectedLearned parametersSequences longer than the training lengthTypical use
Learned positional embedding (this article)Added to the input embeddings (once)Yes (Lmax⁑×dL_{\max} \times d)Cannot be representedBERT, GPT, ViT
Sinusoidal positional encodingAdded to the input embeddings (once)NoneValues can be computed, but accuracy drops sharplyOriginal Transformer
Relative position representationsPer-distance vectors added to the attention scores (and outputs) in each layerYes (2k+12k+1 distances)Computable because distances are clipped at kkTranslation and others
RoPEQueries and keys in each layer rotated by an angle proportional to positionNoneOnly slightly longerMany large language models such as LLaMA
ALiBiA distance-proportional penalty subtracted from the attention scores in each layerNoneTends to keep accuracyWhen using sequences longer than in training
  • When the input length is fixed and a simple implementation is preferred, a learned positional embedding is a good fit. Its accuracy is about the same as sinusoidal, and the code only adds one nn.Embedding.
  • To handle inputs longer than in training at inference, consider ALiBi or RoPE (with position interpolation).
  • When the input size varies, as with images, either interpolate the learned positional embedding or consider a method that generates position from the input, such as CPE.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class LearnedPositionalEmbedding(nn.Module):
    """Learns a table with one vector per position and adds it to the word embeddings"""

    def __init__(self, vocab_size: int, d_model: int, max_len: int = 512, dropout: float = 0.1):
        super().__init__()
        self.tok = nn.Embedding(vocab_size, d_model)   # word embedding table
        self.pos = nn.Embedding(max_len, d_model)      # position embedding table P (max_len Γ— d_model, learned)
        self.max_len = max_len
        self.dropout = nn.Dropout(dropout)             # active only in model.train()

    def forward(self, tokens: torch.Tensor) -> torch.Tensor:
        # tokens: [batch, sequence length]
        n = tokens.size(1)
        if n > self.max_len:
            # positions not in the table cannot be looked up (limitation of learned positional embeddings)
            raise ValueError(f"sequence length {n} exceeds max_len = {self.max_len}")
        positions = torch.arange(n, device=tokens.device)    # 0, 1, ..., n-1
        x = self.tok(tokens) + self.pos(positions)            # e_j = w_j + p_j (the position part is shared across the batch)
        return self.dropout(x)


emb = LearnedPositionalEmbedding(vocab_size=30000, d_model=768, max_len=512)
print(sum(p.numel() for p in emb.pos.parameters()))  # 393216 = 512 Γ— 768

tokens = torch.randint(0, 30000, (2, 20))             # batch 2, length 20
emb.train()
x = emb(tokens)
print(x.shape)  # torch.Size([2, 20, 768])

# An input of length 600 raises an error because the table does not have enough rows
emb.eval()
try:
    emb(torch.randint(0, 30000, (1, 600)))
except ValueError as e:
    print(e)

FAQ

Q. Should I choose this or sinusoidal positional encoding?
A.

In the Transformer paper's comparison, translation accuracy was almost the same (BLEU 25.8 vs. 25.7). If the input length is fixed, a learned positional embedding, which is simpler to implement, is sufficient. To handle inputs longer than in training, both extrapolate poorly, so consider ALiBi or RoPE.

Q. How can inputs longer than the maximum length $L_{\max}$ be handled?
A.

They cannot be handled as is, so the basic approach is to split or truncate the input to Lmax⁑L_{\max} or less. If the table is enlarged and rebuilt, the added rows must be trained. When ViT increases the image resolution, it interpolates the pretrained positional embeddings in 2D before fine-tuning.

Q. For 2D inputs such as images, is a 2D positional embedding better?
A.

In the ViT paper's comparison, the difference between 1D (patches in raster order) and 2D (row and column embeddings concatenated) was small (accuracy 0.642 vs. 0.640). Even a learned 1D positional embedding ends up with similar vectors for nearby patches and for patches in the same row or column, naturally learning the 2D layout.

References

  1. J. Gehring, M. Auli, D. Grangier, D. Yarats, and Y. N. Dauphin, "Convolutional Sequence to Sequence Learning," ICML, 2017.
  2. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  3. J. Devlin, M.-W. Chang, K. Lee, and K. Toutanova, "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding," NAACL, 2019.
  4. A. Radford, K. Narasimhan, T. Salimans, and I. Sutskever, "Improving Language Understanding by Generative Pre-Training," OpenAI, 2018.
  5. A. Dosovitskiy et al., "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale," ICLR, 2021.
  6. O. Press, N. A. Smith, and M. Lewis, "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation," ICLR, 2022.