SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2506.09944 · EMNLP · 2025

Query-Focused Retrieval Heads Improve Long-Context Reasoning and Re-ranking

Wuwei Zhang, ♠ Fangcong, Yin Howard, Yen Danqi, Chen Xi

arXiv · PDF · Open in the Atlas

Code that ran

16 of 18 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 11 have no contract verdict; 5 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-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/2506.09944.json · badge: /api/ran/2506.09944.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-pli/QRHead canonical (classifier label)
classifier basis not recorded on the link
16 ran · 2 no recorded run
FunctionStatusWhere it lives
repeat_kv Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
princeton-pli/QRHead/src/qrretriever/custom_modeling_llama.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-pli/QRHead/src/qrretriever/custom_modeling_qwen2.py
code served (permissive licence) · get_code("d61c483a3c2b3156")
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)

# Construct tiny tensors for the function
batch_size = 2
seq_len = 3
num_heads = 4
head_dim = 8

# Query and key tensors: [batch_size, num_heads, seq_len, head_dim]
q = torch.randn(batch_size, num_heads, seq_len, head_dim)
k = torch.randn(batch_size, num_heads, seq_len, head_dim)

# Cosine and sine embeddings: [seq_len, head_dim]
# These will be indexed by position_ids
cos = torch.randn(seq_len, head_dim)
sin = torch.randn(seq_len, head_dim)

# Position IDs: [batch_size, seq_len]
position_ids = torch.tensor([[0, 1, 2], [0, 1, 2]], dtype=torch.long)

# unsqueeze_dim parameter
unsqueeze_dim = 1

ARGS = {
    "q": q,
    "k": k,
    "cos": cos,
    "sin": sin,
    "position_ids": position_ids,
    "unsqueeze_dim": unsqueeze_dim,
}
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
apply_rotary_pos_emb Ran
ran; our contract draft was wrong, not the code
princeton-pli/QRHead/src/qrretriever/custom_modeling_llama.py
code served (permissive licence) · get_code("bac65c3dafaec040")
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 query and key
# Shape: [batch_size, heads, seq_len, head_dim]
batch_size = 2
heads = 3
seq_len = 4
head_dim = 8

q = torch.randn(batch_size, heads, seq_len, head_dim)
k = torch.randn(batch_size, heads, seq_len, head_dim)

# Create cos and sin tensors
# Shape: [batch_size, seq_len, head_dim]
cos = torch.randn(batch_size, seq_len, head_dim)
sin = torch.randn(batch_size, seq_len, head_dim)

# position_ids is optional and unused according to docstring
position_ids = None

# unsqueeze_dim defaults to 1
unsqueeze_dim = 1

ARGS = {
    "q": q,
    "k": k,
    "cos": cos,
    "sin": sin,
    "position_ids": position_ids,
    "unsqueeze_dim": unsqueeze_dim,
}
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
compute_recall Ran
ran on a synthesized input
princeton-pli/QRHead/exp_scripts/retrieval/eval_retrieval.py
code served (permissive licence) · get_code("6485b6194332b150")
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 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 torch
import numpy as np

# Construct valid arguments for compute_recall function

# Create sample data - list of dictionaries with 'idx' and 'gt_docs' keys
samples = [
    {
        'idx': 0,
        'gt_docs': [1, 3, 5]
    },
    {
        'idx': 1,
        'gt_docs': [2, 4]
    },
    {
        'idx': 2,
        'gt_docs': [0, 1, 2, 3]
    }
]

# Create scores dictionary mapping qid to document scores
scores = {
    '0': {
        '1': 0.95,
        '2': 0.87,
        '3': 0.76,
        '4': 0.65,
        '5': 0.54,
        '6': 0.43
    },
    '1': {
        '2': 0.92,
        '4': 0.88,
        '1': 0.75,
        '3': 0.62,
        '5': 0.51,
        '0': 0.40
    },
    '2': {
        '0': 0.98,
        '1': 0.89,
        '2': 0.81,
        '3': 0.72,
        '4': 0.63,
        '5': 0.52
    }
}

k = 2

ARGS = {
    'samples': samples,
    'scores': scores,
    'k': k
}
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 tuple, ndim 1, 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
generate_prompt Ran
ran on a synthesized input
princeton-pli/QRHead/exp_scripts/generation/run_generation_lme.py
code served (permissive licence) · get_code("f8bf3d9d30b922e6")
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 json

# Build arguments for generate_prompt function

# curr_haystack_dates: list of dates (strings or datetime objects)
curr_haystack_dates = ["2024-01-15", "2024-01-20", "2024-01-25"]

# curr_haystack_sessions: list of session entries
# Each session is a list that may contain dict entries with 'has_answer' and 'round_id' keys
curr_haystack_sessions = [
    [
        {"user": "hello", "assistant": "hi there", "has_answer": True, "round_id": 1},
        {"user": "how are you?", "assistant": "i'm doing well"}
    ],
    [
        {"user": "what's the weather?", "assistant": "sunny", "has_answer": False, "round_id": 2},
        {"user": "thanks", "assistant": "you're welcome"}
    ],
    [
        {"user": "tell me a joke", "assistant": "why did the chicken cross the road?", "has_answer": True, "round_id": 3}
    ]
]

# curr_question: the question string to answer
curr_question = "What was discussed about the weather?"

# curr_question_date: the date of the current question
curr_question_date = "2024-01-26"

ARGS = {
    "curr_haystack_dates": curr_haystack_dates,
    "curr_haystack_sessions": curr_haystack_sessions,
    "curr_question": curr_question,
    "curr_question_date": curr_question_date
}
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
get_anscheck_prompt Ran
ran; our contract draft was wrong, not the code
princeton-pli/QRHead/exp_scripts/generation/eval_generation_lme.py
code served (permissive licence) · get_code("8e4f7c8ecedd17fa")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Sonnet 4.5, prompt python_fixture_v1) 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.

ARGS = {
    'task': 'single-session-user',
    'question': 'What is the capital of France?',
    'answer': 'Paris',
    'response': 'The capital of France is Paris.',
    'abstention': False
}
Setup block drafted by
a language model, Claude Sonnet 4.5, prompt python_fixture_v1
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
get_doc_scores_per_head Ran
ran on a synthesized input
princeton-pli/QRHead/exp_scripts/detection/detect_qrhead_beir.py
code served (permissive licence) · get_code("d81d0dbbee1e8828")
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 dict. 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 random
from torch import nn

torch.manual_seed(0)
random.seed(42)

class MockHeadRetriever(nn.Module):
    """Mock retriever that scores docs per head"""
    def __init__(self):
        super().__init__()
        self.num_heads = 3
        
    def score_docs_per_head_for_detection(self, query, docs):
        """
        Returns a dict mapping head indices to lists of scores for each doc
        """
        scores_per_head = {}
        for head_idx in range(self.num_heads):
            scores_per_head[head_idx] = [random.random() for _ in docs]
        return scores_per_head

# Create mock retriever
full_head_retriever = MockHeadRetriever()

# Create mock data instances
data_instances = [
    {
        'idx': 'doc_1',
        'question': 'What is machine learning?',
        'paragraphs': [
            {
                'paragraph_text': 'Machine learning is a subset of artificial intelligence that focuses on learning from data.',
                'id': 'p1'
            },
            {
                'paragraph_text': 'Deep learning uses neural networks with multiple layers to process information.',
                'id': 'p2'
            }
        ]
    },
    {
        'idx': 'doc_2',
        'question': 'How does neural networks work?',
        'paragraphs': [
            {
                'paragraph_text': 'Neural networks are inspired by biological neurons and process information through interconnected nodes.',
                'id': 'p3'
            },
            {
                'paragraph_text': 'Training neural networks involves adjusting weights to minimize loss on training data.',
                'id': 'p4'
            }
        ]
    }
]

ARGS = {
    'full_head_retriever': full_head_retriever,
    'data_instances': data_instances,
    'truncate_by_space': 0
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, tqdm — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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
get_doc_scores_per_head Ran
ran on a synthesized input
princeton-pli/QRHead/exp_scripts/detection/detect_qrhead_lme.py
code served (permissive licence) · get_code("009654fea103956a")
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 dict. 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 torch.nn as nn

# Define a mock retriever that implements the score_docs_per_head_for_detection method
class MockFullHeadRetriever(nn.Module):
    def __init__(self):
        super().__init__()
    
    def score_docs_per_head_for_detection(self, query, docs):
        """
        Returns a dict mapping head indices to scores for the given query and docs.
        """
        # Return a simple dict with head scores
        scores_dict = {}
        for head_idx in range(2):  # 2 heads
            # Create a list of scores, one per document
            scores_dict[head_idx] = [0.5 + head_idx * 0.1 + doc_idx * 0.05 
                                     for doc_idx in range(len(docs))]
        return scores_dict

# Create the mock retriever
torch.manual_seed(0)
full_head_retriever = MockFullHeadRetriever()

# Create sample data instances with the required structure
data_instances = [
    {
        'idx': 'instance_0',
        'question': 'What is machine learning?',
        'paragraphs': [
            {
                'paragraph_text': 'Machine learning is a subset of artificial intelligence that focuses on enabling computers to learn from data.',
            },
            {
                'paragraph_text': 'Deep learning is a subfield of machine learning based on artificial neural networks.',
            }
        ]
    },
    {
        'idx': 'instance_1',
        'question': 'How does neural networks work?',
        'paragraphs': [
            {
                'paragraph_text': 'Neural networks are computing systems inspired by biological neural networks.',
            },
            {
                'paragraph_text': 'Training a neural network involves adjusting weights to minimize loss.',
            }
        ]
    }
]

# Define ARGS
ARGS = {
    'full_head_retriever': full_head_retriever,
    'data_instances': data_instances,
    'truncate_by_space': 0
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, tqdm — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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
get_top_k_docs Ran
ran on a synthesized input
princeton-pli/QRHead/exp_scripts/retrieval/eval_retrieval.py
code served (permissive licence) · get_code("30515a995de52d2d")
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 torch
import numpy as np
from typing import Dict, List

# Construct arguments for get_top_k_docs
doc_scores = {
    "doc_1": 0.95,
    "doc_2": 0.87,
    "doc_3": 0.72,
    "doc_4": 0.65,
    "doc_5": 0.58,
}

k = 3

ARGS = {
    "doc_scores": doc_scores,
    "k": k,
}
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 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
get_topk_doc_idx Ran
ran on a synthesized input
princeton-pli/QRHead/exp_scripts/generation/run_generation_clipper.py
code served (permissive licence) · get_code("84ed72a7f256783d")
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.

# Construct valid arguments for get_topk_doc_idx

ARGS = {
    "doc_scores": {
        "doc_1": 0.95,
        "doc_2": 0.87,
        "doc_3": 0.72,
        "doc_4": 0.65,
        "doc_5": 0.58,
    },
    "k": 3,
}
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
lme_eval Ran
ran on a synthesized input
princeton-pli/QRHead/exp_scripts/detection/detect_qrhead_lme.py
code served (permissive licence) · get_code("46d639c95b19b2e5")
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 float64, ndim 0, 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 numpy as np

# Set seed for reproducibility
np.random.seed(0)

# Construct retrieval_results
# Format: qid -> {doc_id -> score}
retrieval_results = {
    "q_001": {
        "doc_001": 0.9,
        "doc_002": 0.7,
        "doc_003": 0.5,
        "doc_004": 0.3,
    },
    "q_002": {
        "doc_005": 0.85,
        "doc_006": 0.6,
        "doc_007": 0.4,
        "doc_008": 0.2,
    },
}

# Construct data_instances
# Each dict has 'idx' (qid), 'gt_docs' (list of ground truth doc ids)
data_instances = [
    {
        "idx": "q_001",
        "gt_docs": ["doc_001", "doc_002"],
    },
    {
        "idx": "q_002",
        "gt_docs": ["doc_005"],
    },
]

ARGS = {
    "retrieval_results": retrieval_results,
    "data_instances": data_instances,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type float64, ndim 0, dtype family float — no output shape is stated: observe_signature.py recorded float ndim 0, which disagrees with the fixture run
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_config Ran
ran on a synthesized input
princeton-pli/QRHead/src/qrretriever/config.py
code served (permissive licence) · get_code("229e3b5a73665fb2")
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 dict. 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 tempfile
from pathlib import Path
import yaml

# Create a temporary directory and a temporary config file
temp_dir = tempfile.mkdtemp()
config_dir = Path(temp_dir) / 'configs'
config_dir.mkdir(exist_ok=True)

# Create a default config file
default_config = {
    'model': 'resnet50',
    'batch_size': 32,
    'learning_rate': 0.001,
    'epochs': 100,
    'dataset': 'imagenet'
}

default_config_path = config_dir / 'default.yaml'
with open(default_config_path, 'w') as f:
    yaml.dump(default_config, f)

# Create a custom config file
custom_config = {
    'model': 'vgg16',
    'batch_size': 64,
    'learning_rate': 0.0001,
    'epochs': 50,
    'dataset': 'cifar10'
}

custom_config_path = Path(temp_dir) / 'custom_config.yaml'
with open(custom_config_path, 'w') as f:
    yaml.dump(custom_config, f)

# Define ARGS for the load_config function
ARGS = {
    'config_path': str(custom_config_path)
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
yaml — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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
merge_configs Ran
ran on a synthesized input
princeton-pli/QRHead/src/qrretriever/config.py
code served (permissive licence) · get_code("1b2be7c22837418d")
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 dict. 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 numpy as np
from typing import Dict, Optional, Union

torch.manual_seed(0)

# Create sample default config with nested structure
default_config = {
    "model": {
        "hidden_size": 256,
        "num_layers": 2,
        "dropout": 0.1
    },
    "training": {
        "learning_rate": 0.001,
        "batch_size": 32,
        "epochs": 10
    },
    "seed": 42
}

# Create sample custom config that overrides some defaults
custom_config = {
    "model": {
        "hidden_size": 512
    },
    "training": {
        "learning_rate": 0.0005
    },
    "debug": True
}

ARGS = {
    "default_config": default_config,
    "custom_config": custom_config
}
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 dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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
parse_file Ran
ran on a synthesized input
princeton-pli/QRHead/exp_scripts/generation/eval_generation_clipper.py
code served (permissive licence) · get_code("1340e53f675329ea")
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 json
import tempfile
import os

# Create a temporary file with JSONL content
temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.jsonl', encoding='utf-8')
temp_file.write(json.dumps({'idx': 0, 'hypothesis': 'The answer is <answer>yes</answer> today'}) + '\n')
temp_file.write(json.dumps({'idx': 1, 'hypothesis': 'Some text <answer>NO</answer> more text'}) + '\n')
temp_file.write(json.dumps({'idx': 2, 'hypothesis': 'Missing tag here'}) + '\n')
temp_file.close()

ARGS = {
    'file_path': temp_file.name
}
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
rotate_half Ran
ran; our contract draft was wrong, not the code
princeton-pli/QRHead/src/qrretriever/custom_modeling_llama.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
score_heads Ran
ran on a synthesized input
princeton-pli/QRHead/exp_scripts/detection/detect_qrhead_lme.py
code served (permissive licence) · get_code("b3336deddac204eb")
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.

import torch
import numpy as np

torch.manual_seed(0)

# Build doc_scores_per_head: dict of dicts
# Structure: {qid -> {doc_id -> tensor of shape (num_layers, num_heads)}}
num_layers = 2
num_heads = 3

doc_scores_per_head = {
    "q1": {
        "doc_0": torch.randn(num_layers, num_heads),
        "doc_1": torch.randn(num_layers, num_heads),
    },
    "q2": {
        "doc_0": torch.randn(num_layers, num_heads),
        "doc_2": torch.randn(num_layers, num_heads),
    },
}

# Build data_instances: list of dicts
# Each dict needs 'idx' (qid) and 'gt_docs' (list of ground truth doc ids)
data_instances = [
    {
        'idx': 'q1',
        'gt_docs': ['doc_0'],
    },
    {
        'idx': 'q2',
        'gt_docs': ['doc_2'],
    },
]

ARGS = {
    'doc_scores_per_head': doc_scores_per_head,
    'data_instances': data_instances,
}
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 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
extract_relevant_rounds Not yet run
unverified (harvested, no recorded run)
princeton-pli/QRHead/exp_scripts/generation/run_generation_lme.py
code served (permissive licence) · get_code("63bfa7b825473d3d")
How it ran

no invocation recorded.

prepare_prompt_for_generation Not yet run
unverified (harvested, no recorded run)
princeton-pli/QRHead/exp_scripts/generation/run_generation_clipper.py
code served (permissive licence) · get_code("ff68a23061cdf19a")
How it ran

no invocation recorded.

Also present in other papers' code

Of 18 samples lifted from this paper's linked repositories, 18 carry a function identity and 0 do not. Of the 18 distinct functions with an identity, 5 are also present in other papers whose code we hold (5 with at least one paper dated earlier, 3 the same month, 5 later) and 13 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
282 dated earlier, 10 the same month, 60 later, 5 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
192 dated earlier, 5 the same month, 40 later, 4 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
apply_rotary_pos_emb 94 other papers
64 dated earlier, 4 the same month, 21 later, 2 same year, order not determinable, 3 undated · 6 only as an assembly brick
1901.02860 (2019-01)
Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
2305.17888 (2023-05)
LLM-QAT: Data-Free Quantization Aware Training for Large Language Models
2309.11674 (2023-09)
A Paradigm Shift in Machine Translation: Boosting Translation Performance of Large Language Models
and 91 more not named here
apply_rotary_pos_emb 75 other papers
65 dated earlier, 9 later, 1 same year, order not determinable · 2 only as an assembly brick
2309.11499 (2023-09)
DreamLLM: Synergistic Multimodal Comprehension and Creation
2312.02051 (2023-12)
TimeChat: A Time-sensitive Multimodal Large Language Model for Long Video Understanding
2312.03414 (2023-12)
Compressed Context Memory For Online Language Model Interaction
and 72 more not named here
get_anscheck_prompt 3 other papers
1 dated earlier, 2 later
2410.10813 (2024-10)
LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory
2510.18866 (2025-10)
LightMem: Lightweight and Efficient Memory-Augmented Generation
2601.01280 (2026-01)
Does Memory Need Graphs? A Unified Framework and Empirical Analysis for Long-Term Dialog Memory

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

Recent work has identified retrieval heads (Wu et al., 2025b), a subset of attention heads responsible for retrieving salient information in long-context language models (LMs), as measured by their copy-paste behavior in Needlein-a-Haystack tasks. In this paper, we introduce QRHEAD (Query-Focused Retrieval Head), an improved set of attention heads that enhance retrieval from long context. We identify QRHEAD by aggregating attention scores with respect to the input query, using a handful of examples from real-world tasks (e.g., long-context QA). We further introduce QR-RETRIEVER, an efficient and effective retriever that uses the accumulated attention mass of QRHEAD as retrieval scores. We use QR-RETRIEVER for long-context reasoning by selecting the most relevant parts with the highest retrieval scores. On multi-hop reasoning tasks LongMemEval and CLIPPER, this yields over 10% performance gains over full context and outperforms strong dense retrievers. We also evaluate QRRETRIEVER as a re-ranker on the BEIR benchmark and find that it achieves strong zero-shot performance, outperforming other LLM-based re-rankers such as RankGPT. Further analysis shows that both the querycontext attention scoring and task selection are crucial for identifying QRHEAD with strong downstream utility. Overall, our work contributes a general-purpose retriever and offers interpretability insights into the long-context capabilities of LMs. 1

For agents

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

get_harvested_code_for_paper("2506.09944")
get_code_for_paper("2506.09944")
have("2506.09944")

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

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

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

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

Connect an agent — have() is free.