SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2406.02536 · 2024

Mitigate Position Bias in Large Language Models via Scaling a Single Dimension

arXiv · PDF · Open in the Atlas

Code that ran

17 of 22 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; 3 honoured the contract we drafted, 0 violated it and 0 have no contract verdict; 14 failures of our instrument; 5 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/2406.02536.json · badge: /api/ran/2406.02536.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
PositionalHidden/PositionalHidden canonical (classifier label)
classifier basis: census
17 ran · 5 no recorded run
FunctionStatusWhere it lives
repeat_kv Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
PositionalHidden/PositionalHidden/positional_hidden/models/modeling_gemma_hidden_scale.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)
PositionalHidden/PositionalHidden/positional_hidden/models/modeling_llama_hidden_scale.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
PositionalHidden/PositionalHidden/positional_hidden/models/modeling_gemma_hidden_scale.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
apply_rotary_pos_emb_gemma Ran
ran; our contract draft was wrong, not the code
PositionalHidden/PositionalHidden/positional_hidden/models/modeling_llama_hidden_scale.py
code served (permissive licence) · get_code("061f05dab3ffd652")
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)

# Create small tensors with distinct dimensions
batch_size = 2
seq_len = 3
num_heads = 4
head_dim = 8

# Query tensor: [batch_size, num_heads, seq_len, head_dim]
q = torch.randn(batch_size, num_heads, seq_len, head_dim)

# Key tensor: [batch_size, num_heads, seq_len, head_dim]
k = torch.randn(batch_size, num_heads, seq_len, head_dim)

# Cosine embeddings: [batch_size, seq_len, head_dim]
cos = torch.randn(batch_size, seq_len, head_dim)

# Sine embeddings: [batch_size, seq_len, head_dim]
sin = torch.randn(batch_size, seq_len, head_dim)

# position_ids is deprecated and unused, so None is appropriate
position_ids = None

# unsqueeze_dim specifies where to add dimension for broadcasting
# Since q and k have shape [batch_size, num_heads, seq_len, head_dim],
# unsqueeze_dim=1 will make cos and sin broadcastable
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, 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
best_subspan_em Ran
ran, honoured the contract we drafted
PositionalHidden/PositionalHidden/experiments/lost_in_the_middle/metrics.py
pointer only (licence: MIT); the stored copy get_code serves, from voidism/lookback-lens, is pointer only (licence: NONE) · get_code("10af7cdbc53df7e5")
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 voidism/lookback-lens, 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.

build_mpt_alibi_tensor Ran
ran, honoured the contract we drafted
PositionalHidden/PositionalHidden/positional_hidden/models/modeling_mpt_hidden_scale.py
pointer only (licence: MIT); the stored copy get_code serves, from utkarshsaxena1/eigenattn, is pointer only (licence: NONE) · get_code("6acdafe16c0d4786")
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 utkarshsaxena1/eigenattn, 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.

count_score Ran
ran, honoured the contract we drafted
PositionalHidden/PositionalHidden/experiments/run_on_longbench/metrics.py
code served (permissive licence) · get_code("1051445c95f4d2fc")
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 re

def count_score(prediction, ground_truth, **kwargs):
    prediction = str(prediction)
    numbers = re.findall('\\d+', prediction)
    right_num = 0
    for number in numbers:
        if str(number) == str(ground_truth):
            right_num += 1
    final_score = 0.0 if len(numbers) == 0 else right_num / len(numbers)
    return float(final_score)


ARGS = {
    "prediction": "The answer is 42 and also 42 and 99",
    "ground_truth": 42,
}
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 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
eval_dims Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
PositionalHidden/PositionalHidden/experiments/search_dimension/eval_on_valid_set.py
code served (permissive licence) · get_code("76822e2ad71afee9")
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. 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, 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
from unittest.mock import MagicMock
import pandas as pd

torch.manual_seed(0)

class StandinTokenizer:
    def __init__(self):
        self.chat_template = "[INST] {content} [/INST]"
    
    def encode(self, text, return_tensors=None, padding=False, add_special_tokens=False):
        # Return a simple list of token ids
        return [1, 2, 3, 4, 5]
    
    def apply_chat_template(self, messages, tokenize=False, add_generation_prompt=False):
        return "[INST] " + messages[0]['content'] + " [/INST]"

class StandinConfig:
    def __init__(self):
        self._name_or_path = "gpt2"
        self.hidden_scale_config = {
            'dims': None,
            'last_recompute_tokens': 0
        }

class StandinModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.config = StandinConfig()
        self.linear = nn.Linear(4, 4)
        self.device = torch.device('cpu')
    
    def forward(self, input_ids, attention_mask, labels):
        # Simulate model forward pass
        batch_size = input_ids.shape[0]
        seq_len = input_ids.shape[1]
        
        # Simple loss computation
        logits = self.linear(torch.randn(batch_size, seq_len, 4))
        loss_fn = nn.CrossEntropyLoss()
        loss = loss_fn(logits.view(-1, 4), torch.randint(0, 4, (batch_size * seq_len,)))
        
        output = MagicMock()
        output.loss = loss
        return output

# Create dataset as a DataFrame with input/output columns
dataset = pd.DataFrame({
    'input': ['What is the capital of France?', 'Explain machine learning'],
    'output': ['Paris', 'Machine learning is a subset of AI']
})

model = StandinModel()
tokenizer = StandinTokenizer()
dim_to_scale = [1, 2, 3]

ARGS = {
    'model': model,
    'tokenizer': tokenizer,
    'dataset': dataset,
    'dim_to_scale': dim_to_scale
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
fastchat, pandas, 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
format_chat_prompt Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
PositionalHidden/PositionalHidden/experiments/KV/run_hidden_scale_KV.py
code served (permissive licence) · get_code("b9ac8a016e78383a")
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 torch
import numpy as np
from unittest.mock import MagicMock

torch.manual_seed(0)

# Create a mock tokenizer with chat_template support
class MockTokenizer:
    def __init__(self):
        self.chat_template = "{% for message in messages %}{{ message['role'] }}: {{ message['content'] }}\n{% endfor %}"
    
    def apply_chat_template(self, messages, tokenize=False, add_generation_prompt=False):
        # Simple implementation that formats messages
        result = ""
        for message in messages:
            result += f"{message['role']}: {message['content']}\n"
        if add_generation_prompt:
            result += "assistant: "
        return result

# Test with different model paths
ARGS = {
    "input": "What is 2+2?",
    "model_path": "gpt2",  # Will use the default else branch with tokenizer
    "tokenizer": MockTokenizer()
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
fastchat, numpy, torch — 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
format_chat_prompt Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
PositionalHidden/PositionalHidden/experiments/run_on_longbench/run_on_longbench.py
code served (permissive licence) · get_code("6c56afd9bf4ea601")
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 torch
from unittest.mock import Mock

torch.manual_seed(0)

# Create a mock tokenizer with chat_template support
class MockTokenizer:
    def __init__(self):
        self.chat_template = "{% for message in messages %}{{ message['role'] }}: {{ message['content'] }}\n{% endfor %}"
    
    def apply_chat_template(self, messages, tokenize=False, add_generation_prompt=False):
        prompt = ""
        for message in messages:
            prompt += f"{message['role']}: {message['content']}\n"
        if add_generation_prompt:
            prompt += "assistant: "
        return prompt

ARGS = {
    "input": "What is the capital of France?",
    "model_path": "meta-llama/Llama-2-7b-chat",
    "tokenizer": MockTokenizer(),
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
fastchat, torch — 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
format_chat_prompt Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
PositionalHidden/PositionalHidden/experiments/search_dimension/eval_on_valid_set.py
code served (permissive licence) · get_code("e52c1a2fa822f109")
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 torch
import torch.nn as nn
from unittest.mock import Mock

torch.manual_seed(0)

class MockTokenizer:
    def __init__(self, has_chat_template=True):
        if has_chat_template:
            self.chat_template = "{% for message in messages %}{{ message['role'] }}: {{ message['content'] }}\n{% endfor %}"
        else:
            self.chat_template = None
    
    def apply_chat_template(self, messages, tokenize=False, add_generation_prompt=False):
        result = ""
        for msg in messages:
            result += f"{msg['role']}: {msg['content']}\n"
        if add_generation_prompt:
            result += "assistant: "
        return result

ARGS = {
    "input": "What is the capital of France?",
    "model_path": "gpt2",
    "tokenizer": MockTokenizer(has_chat_template=True)
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
fastchat, torch — 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_model_class Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
PositionalHidden/PositionalHidden/positional_hidden/use_model.py
code served (permissive licence) · get_code("2b1ae840dfdd7e16")
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 type. 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
from unittest.mock import Mock, MagicMock

torch.manual_seed(0)

# Create a mock config that will be returned by AutoConfig.from_pretrained
class MockConfig:
    def __init__(self, architecture):
        self.architectures = [architecture]

# Create a mock AutoConfig.from_pretrained
def mock_from_pretrained(model_path):
    # Return different architectures based on the path
    if 'llama' in model_path.lower():
        return MockConfig('LlamaForCausalLM')
    elif 'mistral' in model_path.lower():
        return MockConfig('MistralForCausalLM')
    elif 'qwen' in model_path.lower():
        return MockConfig('Qwen2ForCausalLM')
    elif 'gemma' in model_path.lower():
        return MockConfig('GemmaForCausalLM')
    elif 'mpt' in model_path.lower():
        return MockConfig('MptForCausalLM')
    else:
        return MockConfig('LlamaForCausalLM')

# Monkey-patch AutoConfig
from transformers import AutoConfig
AutoConfig.from_pretrained = mock_from_pretrained

# Create mock model classes to avoid import errors
class MockLlamaForCausalLM(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 4)

# Patch the imports in the positional_hidden module
import sys
mock_module = MagicMock()
mock_module.LlamaForCausalLM = MockLlamaForCausalLM
mock_module.LlamaFlashAttention2 = MagicMock()
mock_module.LlamaAttention = MagicMock()
mock_module.LlamaSdpaAttention = MagicMock()
mock_module.LlamaAttention._init_hidden_states_scale = MagicMock()

sys.modules['positional_hidden'] = MagicMock()
sys.modules['positional_hidden.models'] = MagicMock()
sys.modules['positional_hidden.models.modeling_llama_hidden_scale'] = mock_module
sys.modules['positional_hidden.models.modeling_gemma_hidden_scale'] = MagicMock()
sys.modules['positional_hidden.models.modeling_mpt_hidden_scale'] = MagicMock()

ARGS = {
    'model_path': 'llama-7b',
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
positional_hidden, torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type type — a type output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a type 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
normalize_answer Ran
ran; our contract draft was wrong, not the code
PositionalHidden/PositionalHidden/experiments/run_on_longbench/metrics.py
pointer only (licence: MIT); the stored copy get_code serves, from borealisai/radar-decoding, is pointer only (licence: LGPL-3.0) · get_code("e7e75981cb464788")
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 borealisai/radar-decoding, and LGPL-3.0, as GitHub detects it on that repository, is not in the permissive set Syntology serves inline. 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
PositionalHidden/PositionalHidden/experiments/lost_in_the_middle/metrics.py
pointer only (licence: MIT); the stored copy get_code serves, from zmzhang2000/trustworthy-alignment, is pointer only (licence: NONE) · get_code("9706a9a0b961096b")
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 zmzhang2000/trustworthy-alignment, 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_zh_answer Ran
ran; our contract draft was wrong, not the code
PositionalHidden/PositionalHidden/experiments/run_on_longbench/metrics.py
pointer only (licence: MIT); the stored copy get_code serves, from borealisai/radar-decoding, is pointer only (licence: LGPL-3.0) · get_code("8c5c581f9264c810")
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 borealisai/radar-decoding, and LGPL-3.0, as GitHub detects it on that repository, is not in the permissive set Syntology serves inline. 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.

prompt_func Ran
ran; our contract draft was wrong, not the code
PositionalHidden/PositionalHidden/experiments/run_on_longbench/run_on_longbench.py
code served (permissive licence) · get_code("e60745782705e531")
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 os
import tempfile

# Create a temporary JSONL file path to simulate a dataset
temp_dir = tempfile.gettempdir()
df_path = os.path.join(temp_dir, "narrativeqa.jsonl")

# Sample input and context strings
input_text = "Who is the main character?"
context_text = "This is a story about a hero who goes on an adventure."

# Construct the ARGS dictionary with all required parameters
ARGS = {
    "df_path": df_path,
    "input": input_text,
    "context": context_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
PositionalHidden/PositionalHidden/positional_hidden/models/modeling_gemma_hidden_scale.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
get_closedbook_qa_prompt Not yet run
unverified (harvested, no recorded run)
PositionalHidden/PositionalHidden/experiments/lost_in_the_middle/prompting.py
code served (permissive licence) · get_code("91506e645c7a9e50")
How it ran

no invocation recorded.

get_hidden_states Not yet run
unverified (harvested, no recorded run)
PositionalHidden/PositionalHidden/experiments/search_dimension/get_avg_hidden_state.py
code served (permissive licence) · get_code("6325cba09a03eb90")
How it ran

no invocation recorded.

get_kv_retrieval_prompt Not yet run
unverified (harvested, no recorded run)
PositionalHidden/PositionalHidden/experiments/lost_in_the_middle/prompting.py
code served (permissive licence) · get_code("aca69348624f921b")
How it ran

no invocation recorded.

get_model_class Not yet run
unverified (harvested, no recorded run)
PositionalHidden/PositionalHidden/experiments/KV/run_hidden_scale_KV.py
code served (permissive licence) · get_code("3fbc0e8f6cb70422")
How it ran

no invocation recorded.

get_qa_prompt Not yet run
unverified (harvested, no recorded run)
PositionalHidden/PositionalHidden/experiments/lost_in_the_middle/prompting.py
code served (permissive licence) · get_code("286b6ac3dc4a717d")
How it ran

no invocation recorded.

Also present in other papers' code

Of 22 samples lifted from this paper's linked repositories, 22 carry a function identity and 0 do not. Of the 22 distinct functions with an identity, 12 are also present in other papers whose code we hold (12 with at least one paper dated earlier, 7 the same month, 9 later) and 10 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
135 dated earlier, 21 the same month, 195 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
79 dated earlier, 16 the same month, 144 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
77 dated earlier, 8 the same month, 47 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 94 other papers
14 dated earlier, 6 the same month, 70 later, 1 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
31 dated earlier, 4 the same month, 40 later · 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
normalize_zh_answer 28 other papers
7 dated earlier, 3 the same month, 16 later, 1 same year, order not determinable, 1 undated
2311.04934 (2023-11)
Prompt Cache: Modular Attention Reuse for Low-Latency Inference
2311.09198 (2023-11)
Never Lost in the Middle: Mastering Long-Context Question Answering with Position-Agnostic Decompositional Training
2024.findings-emnlp.230 (2024 (year only))
CLongEval: A Chinese Benchmark for Evaluating Long-Context Large Language Models
and 25 more not named here
normalize_answer 11 other papers
3 dated earlier, 3 the same month, 5 later
2308.07922 (2023-08)
RAVEN: In-Context Learning with Retrieval-Augmented Encoder-Decoder Language Models
2403.04797 (2024-03)
Found in the Middle: How Language Models Use Long Contexts Better via Plug-and-Play Positional Encoding
2403.15268 (2024-03)
Awakening Augmented Generation: Learning to Awaken Internal Knowledge of Large Language Models for Question Answering
and 8 more not named here
best_subspan_em 5 other papers
2 dated earlier, 3 later
2403.04797 (2024-03)
Found in the Middle: How Language Models Use Long Contexts Better via Plug-and-Play Positional Encoding
2403.15268 (2024-03)
Awakening Augmented Generation: Learning to Awaken Internal Knowledge of Large Language Models for Question Answering
2407.07071 (2024-07)
Lookback Lens: Detecting and Mitigating Contextual Hallucinations in Large Language Models Using Only Attention Maps
and 2 more not named here
build_mpt_alibi_tensor 2 other papers
1 dated earlier, 1 later
2404.10464 (2024-04)
DESTEIN: Navigating Detoxification of Language Models via Universal Steering Pairs and Head-wise Activation Fusion
2408.05646 (2024-08)
Eigen Attention: Attention in Low-Rank Space for KV Cache Compression
get_closedbook_qa_prompt 1 other paper
1 dated earlier
2307.03172 (2023-07)
Lost in the Middle: How Language Models Use Long Contexts
get_kv_retrieval_prompt 1 other paper
1 dated earlier
2307.03172 (2023-07)
Lost in the Middle: How Language Models Use Long Contexts
get_qa_prompt 1 other paper
1 dated earlier
2403.04797 (2024-03)
Found in the Middle: How Language Models Use Long Contexts Better via Plug-and-Play Positional Encoding

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

Large Language Models (LLMs) are increasingly applied in various real-world scenarios due to their excellent generalization capabilities and robust generative abilities. However, they exhibit position bias, also known as "lost in the middle", a phenomenon that is especially pronounced in long-context scenarios, which indicates the placement of the key information in different positions of a prompt can significantly affect accuracy. This paper first explores the micro-level manifestations of position bias, concluding that attention weights are a micro-level expression of position bias. It further identifies that, in addition to position embeddings, causal attention mask also contributes to position bias by creating position-specific hidden states. Based on these insights, we propose a method to mitigate position bias by scaling this positional hidden states. Experiments on the NaturalQuestions Multi-document QA, KV retrieval, LongBench and timeline reorder tasks, using various models including RoPE models, context windowextended models, and Alibi models, demonstrate the effectiveness and generalizability of our approach. Our method can improve performance by up to 15.2% by modifying just one dimension of hidden states. Our code is available at https://aka.ms/PositionalHidden.

For agents

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

get_harvested_code_for_paper("2406.02536")
get_code_for_paper("2406.02536")
have("2406.02536")

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

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

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

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

Connect an agent — have() is free.