AI Logic

Positional Encodings

Conditional Positional Encoding (CPE)

Updated:

How Conditional Positional Encoding (CPE) works. Left: the CPVT pipeline, which adds no positional embedding and inserts a PEG after the first encoder layer. Middle: inside the PEG, the class token is split off, the feature tokens are rearranged into H × W × d, the output of a 3×3 depthwise convolution is added to the original tokens, the result is flattened back into a sequence, and the class token is concatenated. Right: a 6×6 grid of tokens with zero padding, where the window of a corner token includes zeros and a central token sees its surrounding 3×3

What Is Conditional Positional Encoding (CPE)?

Conditional Positional Encoding (CPE) is a method that does not store positional encodings as a fixed table, but instead generates them on the fly with a small convolution over the tokens surrounding each token. Designed for image Transformers (ViT, DeiT), it was posted on arXiv by Chu et al. in 2021 and accepted at ICLR in 2023. The component that produces CPE is called the PEG (Positional Encoding Generator), and a ViT with a PEG inserted is called CPVT.

ViT cuts an image into S×SS \times S patches to form a sequence of tokens and adds learned positional embeddings to convey their order. This approach has two problems specific to images.

  • Weak on image sizes different from training: The table of positional embeddings only covers the image size used in training (for example, 14×14 = 196 entries for 224×224). For larger images the table is interpolated, but accuracy drops without fine-tuning.
  • Does not behave consistently under translation: Since a different vector is added at each position, when an object in the image moves, the positional vectors added to it also change. The property of convolutional neural networks that "if the object moves, the output moves by the same amount" (translation equivariance) breaks down.

CPE solves both problems by generating the positional encoding from each token's neighborhood. As an analogy, instead of handing each person an address on a map (absolute position), each person is asked to look at "who is to my left and who is to my right." Since it only looks at the surroundings, it works the same way even when the venue (image) gets larger. Also, people standing by the wall of the venue can tell they are at the edge because "there is no one next to them," so absolute position is conveyed to some extent as well.

Theory (How the PEG Is Built and Inserted)

Following Figure 2 and the code in Appendix C of the paper, the PEG generates and adds a positional encoding through the following steps. Let the input token sequence be X∈RB×N×CX \in \mathbb{R}^{B \times N \times C} (BB is the batch size, NN the number of feature tokens, and CC the embedding length).

  1. If there is a class token, temporarily remove it from the sequence.
  2. Reshape the feature tokens back into the image layout, X′∈RB×H×W×CX' \in \mathbb{R}^{B \times H \times W \times C} (N=H×WN = H \times W).
  3. Apply a function F\mathcal{F} to the k×kk \times k neighborhood of each position of X′X' to produce the positional encoding E∈RB×H×W×CE \in \mathbb{R}^{B \times H \times W \times C}. The standard F\mathcal{F} is a depthwise convolution with a 3×33 \times 3 kernel, with (k−1)/2(k-1)/2 cells of zero padding around the border.
  4. Add EE to the original tokens.
  5. Flatten back into a sequence and put the removed class token back at the front.

Combining steps 3 and 4 gives the following equation.

Xout′=X′+F(X′),F=DWConvk×k (zero padding (k−1)/2)X'_{\text{out}} = X' + \mathcal{F}(X'), \qquad \mathcal{F} = \mathrm{DWConv}_{k \times k}\ \bigl(\text{zero padding } (k-1)/2\bigr)

The output of F(X′)\mathcal{F}(X') is the CPE at that position. The weights of F\mathcal{F} are learned, but the output varies with the input tokens, which is why it is called a positional encoding "conditioned on the input."

In CPVT, the positional embedding that ViT adds at the input is removed, and one PEG is inserted after the first encoder layer (left of the figure above). Apart from this, the paper's standard configuration is the same as DeiT.

The paper also compares where to insert the PEG. Placing a 3×33 \times 3 PEG before the first encoder layer (right after the patch embedding) gave 70.6%, lower than the 72.4% obtained by placing it after the first layer. The paper explains that after the first layer, each token has passed through attention and carries information about the whole image, so looking at just a 3×33 \times 3 neighborhood already reveals relationships over a wide range. Indeed, even before the first layer, widening the kernel to 27×2727 \times 27 gave 72.5%.

Why Looking Only at the Neighborhood Can Represent Position

The paper sets three requirements for positional encodings for images and states that CPE, which represents neighborhood relationships, satisfies all of them (Section 3.2).

  • Distinguishes order while behaving consistently under translation: Permuting the tokens changes their neighborhoods, so order can be distinguished. On the other hand, when an object in the image is translated, the neighborhood of that object does not change. As a result, the output tends to have the property of shifting by the same amount (translation equivariance).
  • Works as is on sequences longer than in training: Since it only looks at each token's neighborhood, the same convolution can be applied unchanged even when the image gets larger and the number of tokens grows.
  • Absolute position is also known to some extent: Tokens at the edge of the image have zeros from zero padding in their convolution window, so they can tell they are at the edge. Once the edge positions are known, the positions of inner tokens can be traced through the relationships between tokens.

The third point is also confirmed experimentally. Removing only the zero padding from CPVT-Ti lowered the ImageNet top-1 accuracy from 72.4% to 70.5% (Table 11 of the paper).

Strictly speaking, CPE is not translation equivariant. Because zero padding signals the edge positions, the output changes under translation near the edges. The paper itself describes it as "providing a stronger inductive bias toward translation equivariance."

The paper also confirms that the effect of the PEG comes from positional information rather than from the added parameters (Table 5 of the paper).

PEG settingParameterstop-1
None (no positional information)5.68M68.2%
3×33 \times 3, weights randomly initialized and frozen5.68M71.3%
3×33 \times 3, initialized with learned weights and frozen5.68M72.3%
1×11 \times 1 in 12 layers (no neighborhood)6.13M68.6%
3×33 \times 3, learned5.68M72.4%

Even with random frozen weights, accuracy rose by 3.1 points, whereas a 1×11 \times 1 convolution that does not look at the neighborhood rose by only 0.4 points despite having more parameters.

Experimental Results

The results of evaluating models trained on 224×224 images on images of other sizes without fine-tuning are as follows (ImageNet top-1, excerpt from Table 2 of the paper). CPVT uses a PEG consisting of one 3×33 \times 3 depthwise convolution layer, and CPVT-Ti (0-5) inserts one PEG after each of encoder layers 1–5, for a total of 5 PEGs.

Model160224384448512
DeiT-tiny (learned positional embedding)65.6%72.2%71.2%68.8%65.9%
DeiT-tiny (sinusoidal)65.2%72.3%70.8%68.2%65.1%
DeiT-tiny (no positional information)62.1%68.2%68.6%68.4%65.0%
CPVT-Ti66.8%72.4%73.2%71.8%70.3%
CPVT-Ti (0-5)67.7%73.4%74.2%72.6%70.8%

While DeiT's accuracy drops on images larger than in training, CPVT's accuracy rises at 384×384, and the gap with DeiT widens further at 512×512. The same trend holds from small to large models: at 384, DeiT-base reached 79.7% and CPVT-B 82.3%.

Comparing ways of representing position on the same model (DeiT-tiny) gives the following results (Table 7 of the paper).

Position representationtop-1
Learned positional embedding72.2%
2D sinusoidal72.3%
2D relative position representation70.5%
PEG (1)72.4%
PEG (1) + learned positional embedding72.9%
PEG (5)73.4%

The paper attributes the low score of relative position representation to its lack of absolute positional information.

Other main results are as follows.

  • Combination with global average pooling: Classifying with global average pooling (GAP) instead of the class token raised CPVT-Ti from 73.4% to 74.9%. For DeiT-tiny the difference was small, from 72.2% to 72.6%. The paper explains that since GAP is invariant to translation, combining it with translation-equivariant CPE makes the whole model more robust to translation.
  • Almost no increase in parameters or compute: A PEG with one 3×33 \times 3 depthwise convolution layer has 1,728 parameters in CPVT-Ti (d=192d = 192), fewer than DeiT-tiny's positional embedding (192×14×14=37,632192 \times 14 \times 14 = 37{,}632 parameters). The compute is 0.34M FLOPs, negligible compared with the whole model (2.1G FLOPs).
  • Also effective for pyramid Transformers: Replacing PVT-tiny's positional embedding with a PEG improved ImageNet accuracy from 75.0% to 77.3%, and COCO object detection (RetinaNet, 1× schedule) mAP from 36.7 to 38.0. For Swin Transformer-tiny as well, ImageNet accuracy rose from 81.10% to 82.25%.

Practical Considerations

The PEG reshapes the token sequence back into an H×WH \times W image layout before convolving, so it needs to know where each token is located in the image (HH and WW). The method assumes tokens arranged in 2D, like image patches, and cannot be used as is for 1D sequences such as text or for unordered sets. Tokens that do not belong to the image layout, such as the class token, are removed before the convolution and restored afterward.

  • Do not remove zero padding: Zero padding plays the role of conveying absolute position. Removing it lowers accuracy (72.4% → 70.5%).
  • Choose where to insert it: Positions from after the first layer to after the third layer (positions 0–3 in the paper) gave a good result of about 72.4%, while a deep layer (position 10) dropped to 69.0%. When inserting several, the configuration with one after each of layers 1–5 (0-5) worked well, and inserting into all layers (0-11) gave the same 73.4%.
  • A simple F\mathcal{F} is sufficient: A 7×77 \times 7 kernel, a standard convolution, and a stack of 4 layers (with batch normalization and ReLU) were also tried, but all gave 72.3–72.5%, almost the same as a single 3×33 \times 3 depthwise convolution layer (72.4%).
  • The benefit is largest for larger images: If used only on images of the training size, the difference from learned positional embeddings is small (72.2% vs. 72.4%). The advantages are more likely to appear in applications where the input size varies, such as object detection and segmentation.

Comparison with Other Ways of Representing Position

CPE differs from other methods in that it generates positional information from the input itself through convolution, rather than from a "table" or a "function of distance."

MethodWhere position is injectedLearned parametersInputs of a different size from trainingAbsolute positionMain uses
Learned positional embeddingAdded to the input embedding (once)Yes (number of positions × dd)Requires interpolation and fine-tuningYesViT, BERT
Sinusoidal positional encodingAdded to the input embedding (once)NoComputable, but accuracy dropsYesOriginal Transformer
Relative position representationPer-distance vectors added to attention in each layerYes (one vector per distance)Computable because distances are clippedNoTranslation, etc.
RoPERotates queries and keys by position in each layerNoUp to somewhat longer lengthsInner products depend only on relative positionLLaMA, etc.
CPE (this article)Adds the output of a neighborhood convolution between encoder layersYes (only k2×dk^2 \times d)Works as isConveyed by zero paddingCPVT, PVT, and other image Transformers
  • When the image size differs between training and inference (object detection, segmentation, high-resolution inference), CPE is well suited. It requires neither table interpolation nor fine-tuning.
  • When the image size is fixed and you want minimal implementation, the accuracy gap with learned positional embeddings is small.
  • For 1D sequences such as text, methods that inject distance into attention, such as RoPE and ALiBi, are common.

The idea of injecting local relationships through convolution is also close to models that incorporate convolution into a Transformer for 1D signals, such as Conformer for speech recognition. The CPE paper positions itself as using this idea as a positional encoding for 2D images.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class PEG(nn.Module):
  """Positional Encoding Generator (following Algorithm 1 in Appendix C of the paper).
  Reshapes the token sequence into an H×W layout and adds a positional encoding produced by
  a k×k depthwise convolution (zero padding (k-1)/2)."""
  def __init__(self, dim, k=3):
    super().__init__()
    # groups=dim makes it depthwise. Zero padding of padding=k//2 conveys absolute position
    self.proj = nn.Conv2d(dim, dim, k, stride=1, padding=k // 2, groups=dim)

  def forward(self, x, H, W):
    # x: (B, 1 + H*W, C). The first token is the class token
    B, N, C = x.shape
    cls_token, feat = x[:, :1], x[:, 1:]
    feat_2d = feat.transpose(1, 2).reshape(B, C, H, W)   # back to the image layout
    feat_2d = self.proj(feat_2d) + feat_2d               # add the positional encoding F(x)
    feat = feat_2d.flatten(2).transpose(1, 2)            # flatten back into a sequence
    return torch.cat([cls_token, feat], dim=1)          # put the class token back at the front


class CPVT(nn.Module):
  """A small example of a ViT with no positional embedding and a PEG after the first encoder layer (CPVT)"""
  def __init__(self, img_size=224, patch=16, dim=192, depth=12, heads=3, num_classes=1000):
    super().__init__()
    self.patch = patch
    self.patch_embed = nn.Conv2d(3, dim, patch, stride=patch)
    self.cls_token = nn.Parameter(torch.zeros(1, 1, dim))
    self.blocks = nn.ModuleList([
      nn.TransformerEncoderLayer(dim, heads, dim * 4, batch_first=True, norm_first=True, activation='gelu')
      for _ in range(depth)])
    self.peg = PEG(dim)
    self.norm = nn.LayerNorm(dim)
    self.head = nn.Linear(dim, num_classes)

  def forward(self, img):
    x = self.patch_embed(img)                # (B, C, H, W)
    B, C, H, W = x.shape                     # H and W may vary with the image size
    x = x.flatten(2).transpose(1, 2)         # (B, H*W, C). No positional embedding is added
    x = torch.cat([self.cls_token.expand(B, -1, -1), x], dim=1)
    for i, blk in enumerate(self.blocks):
      x = blk(x)
      if i == 0:                             # after the first encoder layer (position 0 in the paper)
        x = self.peg(x, H, W)
    return self.head(self.norm(x)[:, 0])


model = CPVT()
model.eval()
with torch.no_grad():
  print(model(torch.randn(1, 3, 224, 224)).shape)  # the training size
  print(model(torch.randn(1, 3, 384, 384)).shape)  # larger images also work as is (24×24 tokens)

FAQ

Q. What is the biggest difference between CPE and learned positional embeddings?
A.

Where the positional information comes from. Learned positional embeddings keep a table with a fixed vector for each position index and add the same vector regardless of the input. CPE generates it on the fly with a convolution over the tokens around each token, so its value depends on the input and there is no limit set by a table size. As a result, it can be used on images larger than in training without interpolation or fine-tuning (DeiT-tiny drops to 71.2% at 384×384, whereas CPVT-Ti reaches 73.2%).

Q. If it is produced by a convolution, how does it know absolute position?
A.

Thanks to the convolution's zero padding. For tokens at the edge of the image, part of the 3×33 \times 3 window is 0, so they can tell they are at the edge. Tracing relationships from the edges then reveals the positions of inner tokens. Removing zero padding lowered ImageNet top-1 accuracy from 72.4% to 70.5%.

Q. Where and how many PEGs should be inserted?
A.

The paper's standard is one PEG after the first encoder layer (72.4%). Inserting one after each of layers 1–5 raises accuracy to 73.4%, but inserting into all layers gave the same 73.4%. Placing it before the first layer gives a 3×33 \times 3 window too narrow a view, and accuracy drops to 70.6%.

References

  1. X. Chu, Z. Tian, B. Zhang, X. Wang, and C. Shen, "Conditional Positional Encodings for Vision Transformers," ICLR, 2023. arXiv:2102.10882.
  2. H. Touvron, M. Cord, M. Douze, F. Massa, A. Sablayrolles, and H. Jégou, "Training data-efficient image transformers & distillation through attention," arXiv:2012.12877.