SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2402.16617 · ACL · 2024

Long-Context Language Modeling with Parallel Context Encoding

Danqi Chen, Tianyu Gao, Encoder Encoder, Howard Yen

arXiv · PDF · Open in the Atlas

Code that ran

10 of 12 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; 1 honoured the contract we drafted, 0 violated it and 0 have no contract verdict; 9 failures of our instrument; 2 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-22; 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/2402.16617.json · badge: /api/ran/2402.16617.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
princeton-nlp/cepe canonical (classifier label)
classifier basis: census
10 ran · 2 no recorded run
FunctionStatusWhere it lives
repeat_kv Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
princeton-nlp/cepe/modeling_llama_flash.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
apply_rotary_pos_emb Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
princeton-nlp/cepe/modeling_llama_flash.py
code served (permissive licence) · get_code("f725bc2d76076485")
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, 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)

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

# Create cos and sin tensors
# The function squeezes dimensions 1 and 0, then indexes by position_ids
# So we need shape that allows this: (1, 1, seq_len, hidden_dim)
cos = torch.randn(1, 1, 5, 4)
sin = torch.randn(1, 1, 5, 4)

# Create position_ids
# Shape: (batch_size=2, seq_len=3)
position_ids = torch.tensor([[0, 1, 2], [1, 2, 3]])

ARGS = {
    "q": q,
    "k": k,
    "cos": cos,
    "sin": sin,
    "position_ids": position_ids,
}
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, 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
calibrate_nll Ran
ran, honoured the contract we drafted
princeton-nlp/cepe/eval_downstream.py
code served (permissive licence) · get_code("e2d9698be9ebfc0b")
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 1, dtype family float, shape (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 torch.nn as nn

torch.manual_seed(0)

# Minimal tokenizer stand-in
class MinimalTokenizer:
    def __init__(self):
        self.bos_token_id = 1
    
    def __call__(self, texts, return_tensors=None, add_special_tokens=True):
        # Return a mock tokenized output
        class TokenOutput:
            def __init__(self, input_ids):
                self.input_ids = input_ids
        
        # Simple mock: encode each text as small token sequences
        if isinstance(texts, str):
            texts = [texts]
        
        # Create token sequences of varying length based on text
        batch_ids = []
        for text in texts:
            # Simple encoding: use hash to create deterministic token ids
            tokens = [2, 3, 4] if len(text) > 10 else [2, 3]
            batch_ids.append(tokens)
        
        # Pad to same length
        max_len = max(len(ids) for ids in batch_ids)
        padded = [ids + [0] * (max_len - len(ids)) for ids in batch_ids]
        
        input_ids = torch.tensor(padded, dtype=torch.int64)
        
        if return_tensors == 'pt':
            return TokenOutput(input_ids)
        return TokenOutput(input_ids)

# Minimal model that accepts input_ids and returns logits
class MinimalModel(nn.Module):
    def __init__(self, vocab_size=10, hidden_dim=4):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, hidden_dim)
        self.linear = nn.Linear(hidden_dim, vocab_size)
    
    def forward(self, input_ids):
        # input_ids shape: (batch, seq_len)
        embedded = self.embedding(input_ids)  # (batch, seq_len, hidden_dim)
        logits = self.linear(embedded)  # (batch, seq_len, vocab_size)
        
        class Output:
            pass
        
        out = Output()
        out.logits = logits
        return out

# Create instances
tokenizer = MinimalTokenizer()
model = MinimalModel(vocab_size=10, hidden_dim=4)
device = 'cpu'
domain_prompt = "Question: What is 2+2? Answer:"

# Create data dict with options
data = {
    'options': [' 4', ' five', ' 10']
}

ARGS = {
    'data': data,
    'device': device,
    'domain_prompt': domain_prompt,
    'tokenizer': tokenizer,
    'model': model
}
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 1, dtype family float, shape (3,) — shape (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
load_qa_templates Ran
ran; our contract draft was wrong, not the code
princeton-nlp/cepe/dataset_utils.py
pointer only (licence: MIT); the stored copy get_code serves, from Clement25/SharedLLM, is pointer only (licence: NONE) · get_code("c1dc7ad8978154d9")
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 Clement25/SharedLLM, 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.

normalize_answer Ran
ran; our contract draft was wrong, not the code
princeton-nlp/cepe/utils.py
pointer only (licence: MIT); the stored copy get_code serves, from zihangtian/HAPS, is pointer only (licence: NONE) · get_code("6c668580324cfd97")
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 zihangtian/HAPS, 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.

preprocess_alce Ran
ran; our contract draft was wrong, not the code
princeton-nlp/cepe/dataset_utils.py
pointer only (licence: MIT); the stored copy get_code serves, from Clement25/SharedLLM, is pointer only (licence: NONE) · get_code("6ec1f8f1d608c575")
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 Clement25/SharedLLM, 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.

preprocess_demos Ran
ran; our contract draft was wrong, not the code
princeton-nlp/cepe/eval_downstream.py
code served (permissive licence) · get_code("251deacd01d3875f")
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 2, 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.

from collections import defaultdict

# Construct sample demos for testing
demos = [
    {'answer': 'cat', 'question': 'What is a pet?'},
    {'answer': 'dog', 'question': 'What barks?'},
    {'answer': 'cat', 'question': 'What meows?'},
    {'answer': 'dog', 'question': 'What is loyal?'},
]

ARGS = {
    'demos': demos,
    'balanced_sampling': False,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 2, dtype family float — 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
remove_citations Ran
ran; our contract draft was wrong, not the code
princeton-nlp/cepe/utils.py
code served (permissive licence) · get_code("5df8b525aada9853")
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 str. 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 re

def remove_citations(sent):
    return re.sub('\\[\\d+', '', re.sub(' \\[\\d+', '', sent)).replace(' |', '').replace(']', '')

ARGS = {
    'sent': 'This is a sample sentence [1 with citations [2 and more [3 text.'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str 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
rotate_half Ran
ran; our contract draft was wrong, not the code
princeton-nlp/cepe/modeling_llama_flash.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
sample_demos Ran
ran; our contract draft was wrong, not the code
princeton-nlp/cepe/eval_downstream.py
code served (permissive licence) · get_code("268c530f5ecad1f4")
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 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 random
import math

# Construct valid arguments for sample_demos
# The function expects:
# - data: a list of classes, where each class is a list of items
# - num: an integer specifying how many demos to sample

# Create sample data: list of classes, each containing some items
data = [
    ['item_0_0', 'item_0_1', 'item_0_2', 'item_0_3'],  # class 0 with 4 items
    ['item_1_0', 'item_1_1', 'item_1_2'],              # class 1 with 3 items
    ['item_2_0', 'item_2_1', 'item_2_2', 'item_2_3', 'item_2_4']  # class 2 with 5 items
]

num = 5

ARGS = {
    'data': data,
    'num': num
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — 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 float — 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
f1_score Not yet run
unverified (harvested, no recorded run)
princeton-nlp/cepe/utils.py
pointer only (licence: MIT); the stored copy get_code serves, from Clement25/SharedLLM, is pointer only (licence: NONE) · get_code("27f9fcd2b79fea52")
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 Clement25/SharedLLM, 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. No invocation recorded.

load_data Not yet run
unverified (harvested, no recorded run)
princeton-nlp/cepe/dataset_utils.py
pointer only (licence: MIT); the stored copy get_code serves, from Clement25/SharedLLM, is pointer only (licence: NONE) · get_code("45d38779c4dcf77e")
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 Clement25/SharedLLM, 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. No invocation recorded.

Also present in other papers' code

Of 12 samples lifted from this paper's linked repositories, 12 carry a function identity and 0 do not. Of the 12 distinct functions with an identity, 9 are also present in other papers whose code we hold (6 with at least one paper dated earlier, 6 the same month, 9 later) and 3 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
68 dated earlier, 25 the same month, 258 later, 6 same year, order not determinable, 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
33 dated earlier, 19 the same month, 187 later, 2 same year, order not determinable, 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
normalize_answer 133 other papers
59 dated earlier, 8 the same month, 65 later, 1 undated · 1 only as an assembly brick
1508.06615 (2015-08)
Character-Aware Neural Language Models
1606.05250 (2016-06)
SQuAD: 100,000+ Questions for Machine Comprehension of Text
1608.07905 (2016-08)
Machine Comprehension Using Match-LSTM and Answer Pointer
and 130 more not named here
apply_rotary_pos_emb 83 other papers
19 dated earlier, 11 the same month, 51 later, 2 same year, order not determinable · 6 only as an assembly brick
2306.15595 (2023-06)
Extending Context Window of Large Language Models via Positional Interpolation
2307.05695 (2023-07)
ReLoRA: High-Rank Training Through Low-Rank Updates
2307.06945 (2023-07)
In-context Autoencoder for Context Compression in a Large Language Model
and 80 more not named here
f1_score 19 other papers
10 dated earlier, 1 the same month, 8 later
1809.09600 (2018-09)
HOTPOTQA: A Dataset for Diverse, Explainable Multi-hop Question Answering
1905.05460 (2019-05)
Cognitive Graph for Multi-Hop Reading Comprehension at Scale
1911.02896 (2019-11)
Contextualized Sparse Representations for Real-Time Open-Domain Question Answering
and 16 more not named here
remove_citations 7 other papers
2 dated earlier, 1 the same month, 4 later
2305.14627 (2023-05)
Enabling Large Language Models to Generate Text with Citations
2311.07838 (2023-11)
LLatrieval: LLM-Verified Retrieval for Verifiable Generation
2402.04315 (2024-02)
Training Language Models to Generate Text with Citations via Fine-grained Rewards
and 4 more not named here
load_data 1 other paper
1 later
2603.04759 (2026-03)
Stacked from One: Multi-Scale Self-Injection for Context Window Extension
load_qa_templates 1 other paper
1 later
2603.04759 (2026-03)
Stacked from One: Multi-Scale Self-Injection for Context Window Extension
preprocess_alce 1 other paper
1 later
2603.04759 (2026-03)
Stacked from One: Multi-Scale Self-Injection for Context Window Extension

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-22.

Repositories linked to this paper

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

Abstract

Extending large language models (LLMs) to process longer inputs is crucial for a wide range of applications. However, the substantial computational cost of transformers and limited generalization of positional encoding restrict the size of their context window. We introduce Context Expansion with Parallel Encoding (CEPE ), a framework that can be applied to any existing decoder-only LLMs to extend their context window. CEPE employs a small encoder to process long inputs chunk by chunk, enabling the frozen decoder to utilize additional contexts via cross-attention. CEPE is efficient, generalizable, and versatile: trained with 8K-token documents, it extends the context window of LLAMA-2 to 128K tokens, offering 10× the throughput with only 1/6 of the memory. CEPE yields strong performance on language modeling and in-context learning. CEPE also excels in retrieval-augmented applications, while existing long-context models degenerate with retrieved contexts. We further introduce a CEPE variant that can extend the context window of instruction-tuned models using only unlabeled data, and showcase its effectiveness on LLAMA-2-CHAT, leading to a strong instruction-following model that can leverage very long contexts on downstream tasks. 1 Chapter 01: Dune ...

For agents

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

get_harvested_code_for_paper("2402.16617")
get_code_for_paper("2402.16617")
have("2402.16617")

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

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

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

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

Connect an agent — have() is free.