SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2310.16450 · ICLR · 2024

CLEX: Continuous Length Extrapolation for Large Language Models

Xin Li, Bing Lidong, Zaiqiao Meng, Guanzheng Chen, Shangsong Liang

arXiv · PDF · Open in the Atlas

Code that ran

9 of 10 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (2 of them constructed an object rather than computing a result; 2 honoured the contract we drafted, 1 violated it and 2 have no contract verdict; 4 failures of our instrument; 1 no recorded run); 1 of them was also run on the host, not in the jail, by the peer-agreement lane that set its level, 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/2310.16450.json · badge: /api/ran/2310.16450.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
DAMO-NLP-SG/CLEX canonical (classifier label)
classifier basis: census
7 ran · 1 no recorded run
damo-nlp-sg/clex community
Papers with Code archive
2 ran · 0 no recorded run
FunctionStatusWhere it lives
repeat_kv Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
DAMO-NLP-SG/CLEX/CLEX/llama/modeling_llama_clex.py
code served (permissive licence) · get_code("30d7eec482ebf6b1")
How it ran

Ran in Syntology's jail on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 4, dtype family float, shape (2, 6, 5, 4) as a later run recorded it. The image it ran in was not recorded. The comparison behind this sample's level is a different run: the peer-agreement lane ran it again on the host, not in the jail (report dated 2026-09-04T23:09:20Z). 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 a tensor with shape (batch, num_key_value_heads, seqlen, head_dim)
# Using distinct sizes: batch=2, num_key_value_heads=3, seqlen=5, head_dim=4
hidden_states = torch.randn(2, 3, 5, 4)

# n_rep is the repetition factor
n_rep = 2

ARGS = {
    "hidden_states": hidden_states,
    "n_rep": n_rep,
}
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 4, dtype family float, shape (2, 6, 5, 4) — shape (2, 6, 5, 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
CLEXScalingRotaryEmbedding Ran
ran on a synthesized input · constructed an object; no result was computed
damo-nlp-sg/clex/CLEX/clex_layer.py
code served (permissive licence) · get_code("7dc80fb53e148af4")
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 an instance of its own class, CLEXScalingRotaryEmbedding: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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
from torch import nn
import math

torch.manual_seed(0)

# Build a minimal stand-in for rope_scaling dict
rope_scaling = {
    'max_factor': 4,
    'param_factor': 2,
    'act': 'silu',
    'time_dt': 0.1
}

# Define ARGS dict with all parameters for CLEXScalingRotaryEmbedding.__init__
ARGS = {
    'dim': 4,
    'max_position_embeddings': 8,
    'rope_scaling': rope_scaling,
    'base': 10000,
    'device': 'cpu'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, torchdiffeq — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type CLEXScalingRotaryEmbedding — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a CLEXScalingRotaryEmbedding output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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
ODELinear Ran
ran on a synthesized input · constructed an object; no result was computed
damo-nlp-sg/clex/CLEX/clex_layer.py
code served (permissive licence) · get_code("5c1563103cfedd3b")
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 an instance of its own class, ODELinear: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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
from torch import nn
import math

torch.manual_seed(0)

class ODELinear(nn.Module):

    def __init__(self, dim: int, factor, act, base=10000, **kwargs):
        super().__init__()
        self.ode_up_proj = nn.Parameter(torch.empty(dim // 2, factor * dim))
        self.ode_down_proj = nn.Parameter(torch.empty(factor * dim, dim // 2))
        self.dim = dim
        self.base = base
        if act == 'tanh':
            self.act = torch.nn.Tanh()
        elif act == 'silu':
            self.act = torch.nn.SiLU()
        else:
            raise ValueError(f"act must be one of ['tanh', 'silu'], got {act}")
        self.reset_parameters()

    def reset_parameters(self):
        nn.init.kaiming_uniform_(self.ode_up_proj, a=math.sqrt(5))
        nn.init.zeros_(self.ode_down_proj)

    def get_time_embedding(self, t, base=10000, device='cuda', dtype=torch.float32):
        if t < 1:
            alpha = 1
        else:
            alpha = 2 * t - 1
        ntk_base = base * alpha ** (self.dim / (self.dim - 2))
        ntk_inv_freq = 1.0 / ntk_base ** (torch.arange(0, self.dim, 2, dtype=torch.float32).to(device) / self.dim)
        index = torch.arange(0, self.dim, 2, dtype=torch.float32).to(device)
        delta_ntk_freq = -2 * index / (self.dim - 2) * 1 / (base ** (index / self.dim) * alpha ** (index / (self.dim - 2) + 1))
        return (delta_ntk_freq.to(device, dtype=dtype), ntk_inv_freq.to(device, dtype=dtype))

    def forward(self, t, x: torch.Tensor):
        device = x.device
        delta_time, time = self.get_time_embedding(t.to(device), device=device, dtype=x.dtype)
        x = x + torch.log(time)
        time_embed = delta_time / time
        delta_inv_freq = self.act(x @ self.ode_up_proj.float()) @ self.ode_down_proj.float()
        delta_inv_freq = delta_inv_freq + time_embed
        return delta_inv_freq


ARGS = {
    'dim': 4,
    'factor': 2,
    'act': 'tanh',
    'base': 10000,
}
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 ODELinear — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a ODELinear output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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
apply_rotary_pos_emb Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
DAMO-NLP-SG/CLEX/CLEX/llama/modeling_llama_clex.py
code served (permissive licence) · get_code("24a346e190e492a8")
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 tuple, ndim 5, dtype family float; 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)

# Build small tensors for q and k
# Shape: (batch=2, seq_len=3, hidden_dim=4)
q = torch.randn(2, 3, 4)
k = torch.randn(2, 3, 4)

# Build cos and sin tensors
# These are typically indexed by position_ids, so we need enough positions
# Shape: (max_positions=5, hidden_dim=4)
cos = torch.randn(5, 4)
sin = torch.randn(5, 4)

# Build position_ids for q
# Shape: (batch=2, seq_len=3)
position_ids = torch.tensor([[0, 1, 2], [1, 2, 3]])

# Build key_position_ids for k
# Shape: (batch=2, seq_len=3)
key_position_ids = torch.tensor([[0, 1, 2], [1, 2, 3]])

# unsqueeze_dim is an int
unsqueeze_dim = 1

ARGS = {
    "q": q,
    "k": k,
    "cos": cos,
    "sin": sin,
    "position_ids": position_ids,
    "key_position_ids": key_position_ids,
    "unsqueeze_dim": unsqueeze_dim,
}
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 tuple, ndim 5, dtype family float — a tuple 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
chars_token_ratio Ran
ran, honoured the contract we drafted
DAMO-NLP-SG/CLEX/train/dataset.py
code served (permissive licence) · get_code("e5aab3f05887f82f")
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 float, 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
from unittest.mock import Mock

torch.manual_seed(0)

# Create a mock tokenizer that has a tokens() method
class MockTokenizer:
    def __call__(self, text):
        # Simulate tokenization by returning an object with a tokens() method
        # Split on spaces and return mock token object
        token_list = text.split()
        return self.TokenResult(token_list)
    
    class TokenResult:
        def __init__(self, tokens):
            self._tokens = tokens
        
        def tokens(self):
            return self._tokens

# Create a small mock dataset
class MockDataset:
    def __init__(self):
        self.data = [
            {"text": "hello world example"},
            {"text": "another sample text here"},
            {"text": "short one"},
            {"text": "this is a longer example sentence"},
        ]
    
    def __iter__(self):
        return iter(self.data)

# Build the arguments
dataset = MockDataset()
tokenizer = MockTokenizer()
data_column = "text"
nb_examples = 4

ARGS = {
    "dataset": dataset,
    "tokenizer": tokenizer,
    "data_column": data_column,
    "nb_examples": nb_examples,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch, tqdm — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type float, 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
get_context_length Ran
ran, honoured the contract we drafted
DAMO-NLP-SG/CLEX/serve/inference.py
code served (permissive licence) · get_code("ee7e8c78ac9624ed")
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 float, 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

class Config:
    def __init__(self):
        self.max_position_embeddings = 2048
        self.rope_scaling = {
            'max_factor': 2.5
        }

config = Config()

ARGS = {
    'config': config
}
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 float, 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
load_balancing_loss_func Ran
ran, violated the contract we drafted
DAMO-NLP-SG/CLEX/CLEX/mixtral/modeling_mixtral_clex.py
code served (permissive licence) · get_code("74f2d25c8432bf82")
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 gate_logits as a tuple of tensors
# Each tensor represents logits from one layer
# Shape: [batch_size * sequence_length, num_experts]
num_layers = 2
batch_size = 2
sequence_length = 3
num_experts = 4

gate_logits = tuple(
    torch.randn(batch_size * sequence_length, num_experts)
    for _ in range(num_layers)
)

ARGS = {
    "gate_logits": gate_logits,
    "num_experts": num_experts,
    "top_k": 2,
}
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
prepare_logits_processor Ran
ran; our contract draft was wrong, not the code
DAMO-NLP-SG/CLEX/serve/inference.py
pointer only (licence: MIT); the stored copy get_code serves, from x-plug/multi-llm-agent, is pointer only (licence: NONE) · get_code("93c25411cf60d992")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from x-plug/multi-llm-agent, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

rotate_half Ran
ran; our contract draft was wrong, not the code
DAMO-NLP-SG/CLEX/CLEX/llama/modeling_llama_clex.py
code served (permissive licence) · get_code("b99eea6376d1e212")
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 (2, 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

torch.manual_seed(0)

# The function rotate_half takes a single parameter 'x' which is a tensor
# It accesses x.shape[-1] to get the last dimension
# It uses indexing with [..., :] slicing notation
# It calls torch.cat() to concatenate tensors

# Create a small tensor with shape (2, 4) - batch size 2, hidden dim 4
x = torch.randn(2, 4)

ARGS = {
    "x": x
}
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 (2, 4) — shape (2, 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
create_datasets Not yet run
unverified (harvested, no recorded run)
DAMO-NLP-SG/CLEX/train/dataset.py
code served (permissive licence) · get_code("b8f03a1ab044bb33")
How it ran

no invocation recorded.

Also present in other papers' code

Of 10 samples lifted from this paper's linked repositories, 10 carry a function identity and 0 do not. Of the 10 distinct functions with an identity, 3 are also present in other papers whose code we hold (3 with at least one paper dated earlier, 2 the same month, 3 later) and 7 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
rotate_half 360 other papers
28 dated earlier, 10 the same month, 319 later, 3 undated · 30 only as an assembly brick
1901.02860 (2019-01)
Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
2203.08913 (2022-03)
Memorizing Transformers
2302.13971 (2023-02)
LLaMA: Open and Efficient Foundation Language Models
and 357 more not named here
repeat_kv 243 other papers
12 dated earlier, 2 the same month, 227 later, 2 undated · 22 only as an assembly brick
1901.02860 (2019-01)
Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
2203.08913 (2022-03)
Memorizing Transformers
2305.17888 (2023-05)
LLM-QAT: Data-Free Quantization Aware Training for Large Language Models
and 240 more not named here
prepare_logits_processor 4 other papers
1 dated earlier, 3 later
2305.14233 (2023-05)
Enhancing Chat Language Models by Scaling High-quality Instructional Conversations
2312.02614 (2023-12)
Prompt Optimization via Adversarial In-Context Learning
2401.07324 (2024-01)
Small LLMs Are Weak Tool Learners: A Multi-LLM Agent
and 1 more not named here

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

Transformer-based Large Language Models (LLMs) are pioneering advances in many natural language processing tasks, however, their exceptional capabilities are restricted within the preset context window of Transformer. Position Embedding (PE) scaling methods, while effective in extending the context window to a specific length, demonstrate either notable limitations in their extrapolation abilities or sacrificing partial performance within the context window. Length extrapolation methods, although theoretically capable of extending the context window beyond the training sequence length, often underperform in practical longcontext applications. To address these challenges, we propose Continuous Length EXtrapolation (CLEX) for LLMs. We generalise the PE scaling approaches to model the continuous dynamics by ordinary differential equations over the length scaling factor, thereby overcoming the constraints of current PE scaling methods designed for specific lengths. Moreover, by extending the dynamics to desired context lengths beyond the training sequence length, CLEX facilitates the length extrapolation with impressive performance in practical tasks. We demonstrate that CLEX can be seamlessly incorporated into LLMs equipped with Rotary Position Embedding, such as LLaMA and GPT-NeoX, with negligible impact on training and inference latency. Experimental results reveal that CLEX can effectively extend the context window to over 4× or almost 8× training length, with no deterioration in performance. Furthermore, when evaluated on the practical LongBench benchmark, our model trained on a 4k length exhibits competitive performance against state-of-the-art open-source models trained on context lengths up to 32k. Our code is available at https://github.com/DAMO-NLP-SG/CLEX.

For agents

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

get_harvested_code_for_paper("2310.16450")
get_code_for_paper("2310.16450")
have("2310.16450")

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

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

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

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

Connect an agent — have() is free.