SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2107.14222 · ICCV · 2021

Rethinking and Improving Relative Position Encoding for Vision Transformer

Houwen Peng, Jianlong Fu, Minghao Chen, Hongyang Chao, Kan Wu

arXiv · PDF · Open in the Atlas

Code that ran

7 of 9 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 0 have no contract verdict; 7 failures of our instrument; 2 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2107.14222.json · badge: /api/ran/2107.14222.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
microsoft/Cream community
Papers with Code archive
7 ran · 2 no recorded run
FunctionStatusWhere it lives
_rp_2d_cross_cols Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
microsoft/Cream/iRPE/DETR-with-iRPE/models/rpe_attention/irpe.py
code served (permissive licence) · get_code("affb9ad6b732b9e4")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 2, dtype family int, shape (3, 3) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import math

torch.manual_seed(0)

# Create a small 2D difference tensor with shape (L, L, 2)
# L=3 for a small sequence length
L = 3
diff = torch.randn(L, L, 2, dtype=torch.float32)

# Define the kwargs that will be passed to piecewise_index
kwargs = {
    'alpha': 2.0,
    'beta': 4.0,
    'gamma': 1.5,
    'dtype': torch.long
}

ARGS = {
    'diff': diff,
    **kwargs
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family int, shape (3, 3) — shape (3, 3) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_rp_2d_cross_rows Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
microsoft/Cream/iRPE/DETR-with-iRPE/models/rpe_attention/irpe.py
code served (permissive licence) · get_code("434e634a4741440f")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 2, dtype family int, shape (3, 3) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import math

torch.manual_seed(0)

# Create a small 2D difference tensor with shape (L, L, 2)
# L=3 for a small sequence length
L = 3
diff = torch.randn(L, L, 2, dtype=torch.float32)

# Define the kwargs that will be passed to piecewise_index
# These are: alpha, beta, gamma, dtype
alpha = 2.0
beta = 4.0
gamma = 8.0
dtype = torch.long

ARGS = {
    "diff": diff,
    "alpha": alpha,
    "beta": beta,
    "gamma": gamma,
    "dtype": dtype,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family int, shape (3, 3) — shape (3, 3) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_rp_2d_euclidean Ran
ran; our contract draft was wrong, not the code
microsoft/Cream/iRPE/DETR-with-iRPE/models/rpe_attention/irpe.py
code served (permissive licence) · get_code("37c3e0e9c4bac792")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 2, dtype family int, shape (4, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import math

torch.manual_seed(0)

# Create a small 2D difference tensor
# Shape should be (L, L, 2) where L is sequence length
# 2 represents (row_offset, col_offset)
L = 4
diff = torch.randn(L, L, 2)

# Define the kwargs that will be passed to piecewise_index
alpha = 2.0
beta = 3.0
gamma = 2.0
dtype = torch.long

ARGS = {
    "diff": diff,
    "alpha": alpha,
    "beta": beta,
    "gamma": gamma,
    "dtype": dtype,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family int, shape (4, 4) — shape (4, 4) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_rp_2d_product Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
microsoft/Cream/iRPE/DETR-with-iRPE/models/rpe_attention/irpe.py
code served (permissive licence) · get_code("cd9ab56e1ede5e05")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 2, dtype family int, shape (3, 3) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import math

torch.manual_seed(0)

# Create a small 2D difference tensor
# Shape: (L, L, 2) where L=3, representing 2D offsets (row_offset, col_offset)
L = 3
diff = torch.randn(L, L, 2)

# Define the kwargs parameters for piecewise_index
alpha = 1.0
beta = 2.0
gamma = 2.0
dtype = torch.long

ARGS = {
    'diff': diff,
    'alpha': alpha,
    'beta': beta,
    'gamma': gamma,
    'dtype': dtype
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family int, shape (3, 3) — shape (3, 3) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_rp_2d_quant Ran
ran; our contract draft was wrong, not the code
microsoft/Cream/iRPE/DETR-with-iRPE/models/rpe_attention/irpe.py
code served (permissive licence) · get_code("f1ae97ecf9f3f3e1")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 2, dtype family int, shape (3, 3) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import math

torch.manual_seed(0)

# Create a small 2D difference tensor
# Shape: (L, L, 2) where L=3, representing 2D offsets (row_offset, col_offset)
L = 3
diff = torch.randn(L, L, 2, dtype=torch.float32)

# Define kwargs for piecewise_index function
kwargs = {
    'alpha': 2.0,
    'beta': 4.0,
    'gamma': 2.0,
    'dtype': torch.long
}

ARGS = {
    'diff': diff,
    **kwargs
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family int, shape (3, 3) — shape (3, 3) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
get_bucket_ids_2d_without_skip Ran
ran; our contract draft was wrong, not the code
microsoft/Cream/iRPE/DETR-with-iRPE/models/rpe_attention/irpe.py
code served (permissive licence) · get_code("8a9e6d9d71d3c2f8")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import math

torch.manual_seed(0)

# Define the METHOD class
class METHOD:
    EUCLIDEAN = 0
    QUANT = 1
    PRODUCT = 3
    CROSS = 4
    CROSS_ROWS = 41
    CROSS_COLS = 42

# Define piecewise_index function (stub implementation)
@torch.no_grad()
def piecewise_index(relative_position, alpha, beta, gamma, dtype):
    """Stub implementation of piecewise_index"""
    # Convert to appropriate dtype and clamp
    rp = relative_position.float()
    # Simple bucketing: map to indices based on alpha, beta, gamma
    beta_int = int(beta)
    # Clamp and scale
    index = torch.clamp(rp.abs().long(), 0, 2 * beta_int)
    return index

# Define _rp_2d_cross_cols, _rp_2d_cross_rows, etc. (stubs)
@torch.no_grad()
def _rp_2d_cross_cols(diff, **kwargs):
    dis = diff[:, :, 1]
    return piecewise_index(dis, **kwargs)

@torch.no_grad()
def _rp_2d_cross_rows(diff, **kwargs):
    dis = diff[:, :, 0]
    return piecewise_index(dis, **kwargs)

@torch.no_grad()
def _rp_2d_euclidean(diff, **kwargs):
    dis = diff.square().sum(2).float().sqrt().round()
    return piecewise_index(dis, **kwargs)

@torch.no_grad()
def _rp_2d_product(diff, **kwargs):
    beta_int = int(kwargs['beta'])
    S = 2 * beta_int + 1
    r = piecewise_index(diff[:, :, 0], **kwargs) + beta_int
    c = piecewise_index(diff[:, :, 1], **kwargs) + beta_int
    pid = r * S + c
    return pid

@torch.no_grad()
def _rp_2d_quant(diff, **kwargs):
    dis = diff.square().sum(2)
    return piecewise_index(dis, **kwargs)

def get_absolute_positions(height, width, dtype, device):
    rows = torch.arange(height, dtype=dtype, device=device).view(height, 1).repeat(1, width)
    cols = torch.arange(width, dtype=dtype, device=device).view(1, width).repeat(height, 1)
    return torch.stack([rows, cols], 2)

def get_num_buckets(method, alpha, beta, gamma):
    beta_int = int(beta)
    if method == METHOD.PRODUCT:
        num_buckets = (2 * beta_int + 1) ** 2
    else:
        num_buckets = 2 * beta_int + 1
    return num_buckets

# Define get_bucket_ids_2d_without_skip function
@torch.no_grad()
def get_bucket_ids_2d_without_skip(height, width, method, alpha, beta, gamma, dtype):
    """Get bucket IDs for 2D relative position encoding without skip token."""
    pos = get_absolute_positions(height, width, dtype, torch.device('cpu'))
    
    # Compute differences
    diff = pos.unsqueeze(0) - pos.unsqueeze(1)  # (height, width, height, width, 2)
    diff = diff.view(height * width, height * width, 2)
    
    # Select method
    if method == METHOD.EUCLIDEAN:
        bucket_ids = _rp_2d_euclidean(diff, alpha=alpha, beta=beta, gamma=gamma, dtype=dtype)
    elif method == METHOD.QUANT:
        bucket_ids = _rp_2d_quant(diff, alpha=alpha, beta=beta, gamma=gamma, dtype=dtype)
    elif method == METHOD.PRODUCT:
        bucket_ids = _rp_2d_product(diff, alpha=alpha, beta=beta, gamma=gamma, dtype=dtype)
    elif method == METHOD.CROSS_ROWS:
        bucket_ids = _rp_2d_cross_rows(diff, alpha=alpha, beta=beta, gamma=gamma, dtype=dtype)
    elif method == METHOD.CROSS_COLS:
        bucket_ids = _rp_2d_cross_cols(diff, alpha=alpha, beta=beta, gamma=gamma, dtype=dtype)
    else:
        raise ValueError(f"Unknown method: {method}")
    
    return bucket_ids

# Construct ARGS
ARGS = {
    'height': 4,
    'width': 3,
    'method': METHOD.EUCLIDEAN,
    'alpha': 1.0,
    'beta': 2.0,
    'gamma': 1.0,
    'dtype': torch.long,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
piecewise_index Ran
ran; our contract draft was wrong, not the code
microsoft/Cream/iRPE/DETR-with-iRPE/models/rpe_attention/irpe.py
code served (permissive licence) · get_code("5632af974aa9bde4")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 2, dtype family float, shape (3, 3) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import math

torch.manual_seed(0)

# Create a small relative position tensor (L x L)
# Using shape (3, 3) for a small example
relative_position = torch.randn(3, 3)

# Define coefficients for the piecewise index function
alpha = 2.0
beta = 5.0
gamma = 3.0

# Define output dtype
dtype = torch.float32

ARGS = {
    "relative_position": relative_position,
    "alpha": alpha,
    "beta": beta,
    "gamma": gamma,
    "dtype": dtype,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family float, shape (3, 3) — shape (3, 3) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
get_bucket_ids_2d Not yet run
unverified (harvested, no recorded run)
microsoft/Cream/iRPE/DETR-with-iRPE/models/rpe_attention/irpe.py
code served (permissive licence) · get_code("c6d5f9784d683be8")
How it ran

no invocation recorded.

iRPE Not yet run
unverified (harvested, no recorded run)
microsoft/Cream/iRPE/DETR-with-iRPE/models/rpe_attention/irpe.py
code served (permissive licence) · get_code("5bc74c794e5f05ef")
How it ran

no invocation recorded.

Also present in other papers' code

Of 9 samples lifted from this paper's linked repositories, 9 carry a function identity and 0 do not. Of the 9 distinct functions with an identity, 9 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 9 later) and 0 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
_rp_2d_cross_cols
brick of this paper's assembly: helper
2 other papers
2 later · 1 only as an assembly brick
2301.08243 (2023-01)
Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture
2404.08351 (2024-04)
OmniSat: Self-Supervised Modality Fusion for Earth Observation
_rp_2d_cross_rows
brick of this paper's assembly: helper
2 other papers
2 later · 1 only as an assembly brick
2301.08243 (2023-01)
Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture
2404.08351 (2024-04)
OmniSat: Self-Supervised Modality Fusion for Earth Observation
_rp_2d_euclidean
brick of this paper's assembly: helper
2 other papers
2 later · 1 only as an assembly brick
2301.08243 (2023-01)
Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture
2404.08351 (2024-04)
OmniSat: Self-Supervised Modality Fusion for Earth Observation
_rp_2d_product
brick of this paper's assembly: helper
2 other papers
2 later · 1 only as an assembly brick
2301.08243 (2023-01)
Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture
2404.08351 (2024-04)
OmniSat: Self-Supervised Modality Fusion for Earth Observation
_rp_2d_quant
brick of this paper's assembly: helper
2 other papers
2 later · 1 only as an assembly brick
2301.08243 (2023-01)
Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture
2404.08351 (2024-04)
OmniSat: Self-Supervised Modality Fusion for Earth Observation
get_bucket_ids_2d_without_skip
brick of this paper's assembly: helper
2 other papers
2 later · 1 only as an assembly brick
2301.08243 (2023-01)
Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture
2404.08351 (2024-04)
OmniSat: Self-Supervised Modality Fusion for Earth Observation
iRPE
brick of this paper's assembly: entry
2 other papers
2 later
2301.08243 (2023-01)
Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture
2404.08351 (2024-04)
OmniSat: Self-Supervised Modality Fusion for Earth Observation
piecewise_index
brick of this paper's assembly: helper
2 other papers
2 later · 1 only as an assembly brick
2301.08243 (2023-01)
Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture
2404.08351 (2024-04)
OmniSat: Self-Supervised Modality Fusion for Earth Observation
get_bucket_ids_2d
brick of this paper's assembly: helper
1 other paper
1 later
2404.08351 (2024-04)
OmniSat: Self-Supervised Modality Fusion for Earth Observation

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Relative position encoding (RPE) is important for transformer to capture sequence ordering of input tokens. General efficacy has been proven in natural language processing. However, in computer vision, its efficacy is not well studied and even remains controversial, e.g., whether relative position encoding can work equally well as absolute position? In order to clarify this, we first review existing relative position encoding methods and analyze their pros and cons when applied in vision transformers. We then propose new relative position encoding methods dedicated to 2D images, called image RPE (iRPE). Our methods consider directional relative distance modeling as well as the interactions between queries and relative position embeddings in self-attention mechanism. The proposed iRPE methods are simple and lightweight. They can be easily plugged into transformer blocks. Experiments demonstrate that solely due to the proposed encoding methods, DeiT [21] and DETR [1] obtain up to 1.5% (top-1 Acc) and 1.3% (mAP) stable improvements over their original versions on ImageNet and COCO respectively, without tuning any extra hyperparameters such as learning rate and weight decay. Our ablation and analysis also yield interesting findings, some of which run counter to previous understanding. Code and models are open-sourced at https://github.com/microsoft/Cream/tree/main/iRPE.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2107.14222")
get_code_for_paper("2107.14222")
have("2107.14222")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2107.14222.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2107.14222.svg)](https://syntology.ai/paper/2107.14222)

Connect an agent — have() is free.