SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2305.19466 · NeurIPS · 2023

The Impact of Positional Encoding on Length Generalization in Transformers

Payel Das, Karthikeyan Ramamurthy, Siva Reddy, Inkit Padhi, Amirhossein Kazemnejad

arXiv · PDF · Open in the Atlas

Code that ran

6 of 7 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 6 have no contract verdict; 0 failures of our instrument; 1 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/2305.19466.json · badge: /api/ran/2305.19466.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
McGill-NLP/length-generalization canonical (classifier label)
classifier basis: census
6 ran · 1 no recorded run
FunctionStatusWhere it lives
compute_distance_two_matrix Ran
ran on a synthesized input
McGill-NLP/length-generalization/src/analyzers/attention_kl_analyzer.py
code served (permissive licence) · get_code("021102deccc6bc0e")
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, through the batch API) and returned float32, ndim 0, dtype family float, shape () 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 numpy as np

torch.manual_seed(0)

# Create two small triangular matrices for testing
# Shape (seq_len, seq_len) where we access m[l, :l+1]
# Using shape (4, 4) to keep it small
m1 = torch.rand(4, 4)
m2 = torch.rand(4, 4)

# Ensure values are positive for KL divergence (probabilities)
m1 = torch.nn.functional.softmax(m1, dim=-1)
m2 = torch.nn.functional.softmax(m2, dim=-1)

ARGS = {
    "m1": m1,
    "m2": m2,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type float32, ndim 0, dtype family float, shape () — shape () 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
compute_max_attention_indices Ran
ran on a synthesized input
McGill-NLP/length-generalization/src/analyzers/attention_aggregate_analyzer.py
code served (permissive licence) · get_code("1673f39a9c76c635")
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, through the batch API) and returned list, ndim 1, dtype family int; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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

torch.manual_seed(0)

# Create a small attention map tensor
# Shape: (seq_len, seq_len) where seq_len = 4
# This represents attention scores for a sequence of length 4
attn_map = torch.randn(4, 4)

ARGS = {
    "attn_map": attn_map
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 1, dtype family int — a list output has no array shape of its own; none is stated
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
takes_arg Ran
ran on a synthesized input
McGill-NLP/length-generalization/src/common/from_params.py
code served (permissive licence) · get_code("f700ed5e563b713e")
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, through the batch API) and returned bool, ndim 0, dtype family float, shape () 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 inspect
import torch
import torch.nn as nn

class ConfigurationError(Exception):
    """
    The exception raised by any AllenNLP object when it's misconfigured
    (e.g. missing properties, invalid properties, unknown properties).
    """

    def __reduce__(self):
        return (type(self), (self.message,))

    def __init__(self, message: str):
        super().__init__()
        self.message = message

    def __str__(self):
        return self.message


def takes_arg(obj, arg: str) -> bool:
    """
    Checks whether the provided obj takes a certain arg.
    If it's a class, we're really checking whether its constructor does.
    If it's a function or method, we're checking the object itself.
    Otherwise, we raise an error.
    """
    if inspect.isclass(obj):
        signature = inspect.signature(obj.__init__)
    elif inspect.ismethod(obj) or inspect.isfunction(obj):
        signature = inspect.signature(obj)
    else:
        raise ConfigurationError(f'object {obj} is not callable')
    return arg in signature.parameters


# Test objects for takes_arg
class TestClass:
    def __init__(self, x: int, y: str):
        pass


def test_function(a, b, c):
    pass


class AnotherClass:
    def __init__(self, param1, param2, param3):
        pass


# Prepare ARGS
ARGS = {
    "obj": TestClass,
    "arg": "x"
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, ndim 0, dtype family float, shape () — shape () 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
takes_kwargs Ran
ran on a synthesized input
McGill-NLP/length-generalization/src/common/from_params.py
code served (permissive licence) · get_code("50574225e4d429d0")
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, through the batch API) and returned bool, ndim 0, dtype family float, shape () 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 inspect
from typing import Any, Union, Tuple

class ConfigurationError(Exception):
    """
    The exception raised by any AllenNLP object when it's misconfigured
    (e.g. missing properties, invalid properties, unknown properties).
    """

    def __reduce__(self) -> Union[str, Tuple[Any, ...]]:
        return (type(self), (self.message,))

    def __init__(self, message: str):
        super().__init__()
        self.message = message

    def __str__(self):
        return self.message

def takes_kwargs(obj) -> bool:
    """
    Checks whether a provided object takes in any positional arguments.
    Similar to takes_arg, we do this for both the __init__ function of
    the class or a function / method
    Otherwise, we raise an error
    """
    if inspect.isclass(obj):
        signature = inspect.signature(obj.__init__)
    elif inspect.ismethod(obj) or inspect.isfunction(obj):
        signature = inspect.signature(obj)
    else:
        raise ConfigurationError(f'object {obj} is not callable')
    return any((p.kind == inspect.Parameter.VAR_KEYWORD for p in signature.parameters.values()))


# Test objects for the takes_kwargs function

class ClassWithKwargs:
    def __init__(self, a: int, **kwargs):
        pass

class ClassWithoutKwargs:
    def __init__(self, a: int, b: str):
        pass

def function_with_kwargs(x, **kwargs):
    pass

def function_without_kwargs(x, y):
    pass

class SimpleCallable:
    def __call__(self, a: int):
        pass

ARGS = {
    "obj": ClassWithKwargs
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, ndim 0, dtype family float, shape () — shape () 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
torch_compute_jensen_shannon_divergence Ran
ran on a synthesized input
McGill-NLP/length-generalization/src/analyzers/attention_kl_analyzer.py
code served (permissive licence) · get_code("0652e08580a50a15")
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, through the batch API) and returned Tensor, ndim 0, dtype family float, shape () 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

torch.manual_seed(0)

# Create two probability distributions with the same shape
# The function expects tensors/arrays that can be converted to tensors
# and used with log() and KL divergence operations
# These should be valid probability distributions (positive values)

p = torch.tensor([
    [0.25, 0.25, 0.25, 0.25],
    [0.1, 0.2, 0.3, 0.4]
], dtype=torch.float32)

q = torch.tensor([
    [0.1, 0.2, 0.3, 0.4],
    [0.25, 0.25, 0.25, 0.25]
], dtype=torch.float32)

ARGS = {
    'p': p,
    'q': q
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
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 0, dtype family float, shape () — shape () 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
torch_compute_symmetric_kl Ran
ran on a synthesized input
McGill-NLP/length-generalization/src/analyzers/attention_kl_analyzer.py
code served (permissive licence) · get_code("3dcd63d94b978c74")
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, through the batch API) and returned Tensor, ndim 0, dtype family float, shape () 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

torch.manual_seed(0)

# The function takes two parameters: p and q
# Looking at the function body:
# - Both p and q are converted to tensors
# - They must have the same shape (asserted)
# - They are used with .log() (so they should be positive values)
# - They are passed to KLDivLoss which expects probability distributions
# - For KLDivLoss with log_target=False, p should be log-probabilities and q should be probabilities

# Create valid probability distributions
# Use shape (2, 4) - batch size 2, dimension 4
p_values = torch.nn.functional.softmax(torch.randn(2, 4), dim=-1)
q_values = torch.nn.functional.softmax(torch.randn(2, 4), dim=-1)

ARGS = {
    'p': p_values,
    'q': q_values,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
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 0, dtype family float, shape () — shape () 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
ConvertSMVer2Cores Not yet run
unverified (harvested, no recorded run)
McGill-NLP/length-generalization/src/common/gpu_utils.py
code served (permissive licence) · get_code("292f2f8aa3c972d1")
How it ran

no invocation recorded.

Also present in other papers' code

Of 7 samples lifted from this paper's linked repositories, 7 carry a function identity and 0 do not. Of the 7 distinct functions with an identity, 1 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 0 the same month, 0 later) and 6 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
ConvertSMVer2Cores 1 other paper
1 dated earlier
2110.06623 (2021-10)
SSSNET: Semi-Supervised Signed Network Clustering

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

Length generalization, the ability to generalize from small training context sizes to larger ones, is a critical challenge in the development of Transformer-based language models. Positional encoding (PE) has been identified as a major factor influencing length generalization, but the exact impact of different PE schemes on extrapolation in downstream tasks remains unclear. In this paper, we conduct a systematic empirical study comparing the length generalization performance of decoder-only Transformers with five different position encoding approaches including Absolute Position Embedding (APE), T5's Relative PE, ALiBi, and Rotary, in addition to Transformers without positional encoding (NoPE). Our evaluation encompasses a battery of reasoning and mathematical tasks. Our findings reveal that the most commonly used positional encoding methods, such as ALiBi, Rotary, and APE, are not well suited for length generalization in downstream tasks. More importantly, NoPE outperforms other explicit positional encoding methods while requiring no additional computation. We theoretically demonstrate that NoPE can represent both absolute and relative PEs, but when trained with SGD, it mostly resembles T5's Relative PE attention patterns. Finally, we find that scratchpad is not always helpful to solve length generalization and its format highly impacts the model's performance. Overall, our work suggests that explicit position encodings are not essential for decoder-only Transformers to generalize well to longer sequences. 37th Conference on Neural Information Processing Systems (NeurIPS 2023).

For agents

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

get_harvested_code_for_paper("2305.19466")
get_code_for_paper("2305.19466")
have("2305.19466")

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

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

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

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

Connect an agent — have() is free.