SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2407.03856 · ICLR · 2025

Q-Adapter: Customizing Pre-trained LLMs to New Preferences with Forgetting Mitigation

Bo An, Yang Yu, Lei Yuan, Zongzhang Zhang, Yi-Chen Li, Fuxiang Zhang, Wenjie Qiu, Chengxing Jia

arXiv · PDF · Open in the Atlas

Code that ran

13 of 14 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 0 have no contract verdict; 13 failures of our instrument; 1 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2407.03856.json · badge: /api/ran/2407.03856.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
LAMDA-RL/Q-Adapter canonical (classifier label)
classifier basis: census
11 ran · 1 no recorded run
mansicer/Q-Adapter canonical (classifier label)
classifier basis: classifier_2025
2 ran · 0 no recorded run
FunctionStatusWhere it lives
chat_template_preprocess Ran
ran; our contract draft was wrong, not the code
LAMDA-RL/Q-Adapter/utils/datasets.py
code served (permissive licence) · get_code("087b6200b29a1f20")
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
from transformers import PreTrainedTokenizer
from unittest.mock import MagicMock

torch.manual_seed(0)

class StandInTokenizer:
    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):
        result = ""
        if isinstance(messages, list):
            for msg in messages:
                if isinstance(msg, dict):
                    result += f"{msg.get('role', 'user')}: {msg.get('content', '')}\n"
        
        if add_generation_prompt:
            result += "assistant: "
        
        if tokenize:
            return [1, 2, 3]
        return result

data_sample = {
    'chosen': [
        {'role': 'user', 'content': 'Hello'},
        {'role': 'assistant', 'content': 'Hi there!'}
    ],
    'rejected': [
        {'role': 'user', 'content': 'Hello'},
        {'role': 'assistant', 'content': 'Goodbye.'}
    ]
}

tokenizer = StandInTokenizer()

ARGS = {
    'data_sample': data_sample,
    'tokenizer': tokenizer
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — 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
collator Ran
ran; our contract draft was wrong, not the code
LAMDA-RL/Q-Adapter/ppo_train.py
code served (permissive licence) · get_code("fddcce152bc7d3bd")
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

torch.manual_seed(0)

# The collator function takes a list of dictionaries and reorganizes them
# by key, collecting all values for each key into separate lists.
# We need to construct a list of dictionaries where each dict has the same keys.

data = [
    {
        "input_ids": torch.tensor([1, 2, 3, 4]),
        "attention_mask": torch.tensor([1, 1, 1, 0]),
        "label": 0
    },
    {
        "input_ids": torch.tensor([5, 6, 7, 8]),
        "attention_mask": torch.tensor([1, 1, 1, 1]),
        "label": 1
    }
]

ARGS = {
    "data": data
}
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
get_transformers_model Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
LAMDA-RL/Q-Adapter/utils/models.py
code served (permissive licence) · get_code("f7380188a0e8cdc9")
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 MinimalCausalLMModel. 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 torch import nn
from unittest.mock import Mock, MagicMock, patch
import tempfile
import os

torch.manual_seed(0)

# Create a minimal tokenizer mock with required attributes
class MinimalTokenizer:
    def __init__(self):
        self.pad_token_id = 0
        self.eos_token_id = 2
        self.bos_token_id = 1
        self.vocab_size = 100

# Create a minimal model mock that satisfies the function's usage
class MinimalCausalLMModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.config = Mock()
        self.config.pad_token_id = None
        self.linear = nn.Linear(4, 4)
    
    def forward(self, input_ids, attention_mask=None):
        return Mock(logits=self.linear(torch.randn(2, 4)))
    
    @classmethod
    def from_pretrained(cls, model_path, torch_dtype=None, device_map=None, 
                       quantization_config=None, trust_remote_code=None):
        model = cls()
        model.config.pad_token_id = None
        return model

# Create a minimal LoRA config mock
class MinimalLoRAConfig:
    def __init__(self, r=8, lora_alpha=16, target_modules=None, lora_dropout=0.05, bias='none'):
        self.r = r
        self.lora_alpha = lora_alpha
        self.target_modules = target_modules or ['q_proj', 'v_proj']
        self.lora_dropout = lora_dropout
        self.bias = bias

# Create a model with print_trainable_parameters method
class MinimalPEFTModel(nn.Module):
    def __init__(self, base_model):
        super().__init__()
        self.base_model = base_model
        self.config = base_model.config
    
    def print_trainable_parameters(self):
        pass
    
    @classmethod
    def from_pretrained(cls, model, lora_path):
        return cls(model)

# Patch the actual imports
with patch('transformers.AutoModelForCausalLM', MinimalCausalLMModel):
    with patch('peft.PeftModel.from_pretrained', return_value=MinimalPEFTModel(MinimalCausalLMModel())):
        with patch('peft.prepare_model_for_kbit_training', side_effect=lambda x: x):
            with patch('peft.LoraConfig', MinimalLoRAConfig):
                with patch('peft.get_peft_model', side_effect=lambda model, config: MinimalPEFTModel(model)):
                    
                    tokenizer = MinimalTokenizer()
                    base_model = "gpt2"
                    model_class = MinimalCausalLMModel
                    
                    ARGS = {
                        'base_model': base_model,
                        'tokenizer': tokenizer,
                        'model_class': model_class,
                        'lora_path': '',
                        'lora_r': 0,
                        'lora_alpha': 16,
                        'lora_dropout': 0.05,
                        'lora_target_modules': ['q_proj', 'v_proj'],
                        'device_map': 'cpu',
                        'load_in_8bit': False,
                    }
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
peft, torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type MinimalCausalLMModel — a MinimalCausalLMModel output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a MinimalCausalLMModel 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_transformers_tokenizer Ran
ran; our contract draft was wrong, not the code
LAMDA-RL/Q-Adapter/utils/models.py
code served (permissive licence) · get_code("aa635e3b36eacb87")
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 MockTokenizer. 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 Mock, MagicMock

torch.manual_seed(0)

# Create a mock tokenizer that behaves like a HuggingFace tokenizer
class MockTokenizer:
    def __init__(self):
        self.eos_token_id = 2
        self.pad_token_id = None
        self.padding_side = 'left'
    
    @classmethod
    def from_pretrained(cls, tokenizer_path, trust_remote_code=True):
        return cls()

# Patch AutoTokenizer to return our mock
import transformers
original_auto_tokenizer = transformers.AutoTokenizer
transformers.AutoTokenizer.from_pretrained = MockTokenizer.from_pretrained

ARGS = {
    'tokenizer_path': 'gpt2',
    'padding_side': 'right'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type MockTokenizer — a MockTokenizer output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a MockTokenizer 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
hash_args Ran
ran; our contract draft was wrong, not the code
mansicer/Q-Adapter/lm-evaluation-harness/lm_eval/api/model.py
code served (permissive licence) · get_code("20a7cc804eb22661")
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 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 hashlib
import json

# Construct valid arguments for hash_args function
# The function takes attr (attribute name) and args (tuple/list of arguments)
# and creates a JSON string to hash

attr = "test_attribute"
args = ("value1", 42, [1, 2, 3], {"key": "value"})

ARGS = {
    "attr": attr,
    "args": args
}
Setup block drafted by
a language model, Claude Haiku 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
init_transformers_model Ran
ran; our contract draft was wrong, not the code
LAMDA-RL/Q-Adapter/utils/models.py
code served (permissive licence) · get_code("c4491a6621f89556")
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 MockModel. 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 transformers import AutoModelForCausalLM, AutoTokenizer
from unittest.mock import Mock, patch, MagicMock

torch.manual_seed(0)

# Create a minimal mock tokenizer with the required pad_token_id attribute
class MockTokenizer:
    def __init__(self):
        self.pad_token_id = 0

# Create a minimal mock model class that returns a model with config
class MockModel(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.config = Mock()
        self.config.pad_token_id = None
        self.linear = torch.nn.Linear(4, 4)
    
    @classmethod
    def from_pretrained(cls, model_path, torch_dtype=None, device_map=None, quantization_config=None, trust_remote_code=None):
        return cls()

# Prepare arguments
tokenizer = MockTokenizer()
model_class = MockModel
model_path = "meta-llama/Llama-2-7b"
device_map = "cpu"
load_in_8bit = False
dtype = torch.float16

ARGS = {
    "model_class": model_class,
    "model_path": model_path,
    "tokenizer": tokenizer,
    "device_map": device_map,
    "load_in_8bit": load_in_8bit,
    "dtype": dtype
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type MockModel — a MockModel output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a MockModel 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
modify_forward Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
LAMDA-RL/Q-Adapter/utils/q_adapter.py
code served (permissive licence) · get_code("11bfc577314806ff")
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 PeftModelForCausalLM. 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
import torch.nn.functional as F
from peft.peft_model import PeftModelForCausalLM
from transformers.modeling_outputs import CausalLMOutputWithPast

torch.manual_seed(0)

class MockPeftModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 5)
    
    def forward(self, input_ids=None, attention_mask=None, inputs_embeds=None, 
                labels=None, output_attentions=None, output_hidden_states=None, 
                return_dict=None, past_key_values=None, **kwargs):
        if inputs_embeds is None:
            inputs_embeds = self.linear(torch.randn(2, 3, 4))
        
        batch_size = 2
        seq_len = 3
        vocab_size = 5
        logits = torch.randn(batch_size, seq_len, vocab_size)
        
        return CausalLMOutputWithPast(
            loss=None,
            logits=logits,
            past_key_values=None,
            hidden_states=None,
            attentions=None
        )
    
    def disable_adapter(self):
        class ContextManager:
            def __enter__(self):
                return self
            def __exit__(self, exc_type, exc_val, exc_tb):
                pass
        return ContextManager()

peft_model = MockPeftModel()
peft_model.__class__ = type('PeftModelForCausalLM', (MockPeftModel,), {})

alpha_tilde = 0.1
alpha_0 = 0.5
gamma = 0.99
beta = 0.1
register_callback = False

ARGS = {
    'peft_model': peft_model,
    'alpha_tilde': alpha_tilde,
    'alpha_0': alpha_0,
    'gamma': gamma,
    'beta': beta,
    'register_callback': register_callback
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, peft, torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type PeftModelForCausalLM — a PeftModelForCausalLM output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a PeftModelForCausalLM 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
modify_prepare_inputs_for_generation Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
LAMDA-RL/Q-Adapter/utils/q_adapter.py
code served (permissive licence) · get_code("4efbafd90b8d3d01")
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 MockPeftModelForCausalLM. 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 peft.peft_model import PeftModelForCausalLM
from transformers import AutoConfig, AutoModelForCausalLM

torch.manual_seed(0)

# Create a minimal mock model that satisfies the PeftModelForCausalLM interface
class MockPeftModelForCausalLM(nn.Module):
    def __init__(self):
        super().__init__()
        self.lm_head = nn.Linear(4, 100)
        self.model = nn.Linear(4, 4)
        
    def __original_prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs):
        """Mock original method that returns a dict with typical generation inputs"""
        return_dict = {
            'input_ids': input_ids,
            'attention_mask': attention_mask,
        }
        if past_key_values is not None:
            return_dict['past_key_values'] = past_key_values
        if inputs_embeds is not None:
            return_dict['inputs_embeds'] = inputs_embeds
        return return_dict
    
    def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs):
        """Default prepare_inputs_for_generation to be replaced"""
        return self.__original_prepare_inputs_for_generation(
            input_ids, 
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            **kwargs
        )

# Instantiate the mock model
peft_model = MockPeftModelForCausalLM()

# Ensure the model has the method we'll be wrapping
peft_model.prepare_inputs_for_generation = peft_model.prepare_inputs_for_generation.__get__(peft_model, type(peft_model))

ARGS = {
    "peft_model": peft_model,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
peft, torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type MockPeftModelForCausalLM — a MockPeftModelForCausalLM output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a MockPeftModelForCausalLM 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_eval_args Ran
ran; our contract draft was wrong, not the code
LAMDA-RL/Q-Adapter/lm-evaluation-harness/lm_eval/__main__.py
pointer only (licence: Apache-2.0); the stored copy get_code serves, from BatsResearch/crosslingual-test-time-scaling, is pointer only (licence: NONE) · get_code("400ea4f64ccce5ef")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (Apache-2.0), but get_code serves the stored copy, first harvested from BatsResearch/crosslingual-test-time-scaling, 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.

qadapter_loss Ran
ran; our contract draft was wrong, not the code
mansicer/Q-Adapter/utils/q_adapter.py
code served (permissive licence) · get_code("ee04f1495c3243f8")
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 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 torch.nn.functional as F

torch.manual_seed(0)

# Analyze the function to understand what's needed:
# - q_values_ai: tensor, used in arithmetic and masking operations
# - values: tensor, used in arithmetic and masking operations
# - mask: tensor, used for masking (multiplication), .sum(), .expand_as()
# - gamma: scalar, used in arithmetic
# - beta: scalar, used in arithmetic (default 0.1)
#
# The function expects:
# - reward_sum.shape[0] to be even (divided by 2 for bs)
# - reward.shape[1] to exist (for normalization)
# - mask to be broadcastable with reward

# Create small tensors with distinct dimensions
batch_size = 4  # Will be divided by 2, so bs=2
seq_len = 3     # Sequence/time dimension

# q_values_ai: shape (batch_size, seq_len)
q_values_ai = torch.randn(batch_size, seq_len)

# values: shape (batch_size, seq_len)
values = torch.randn(batch_size, seq_len)

# mask: shape (batch_size, seq_len) - binary mask
mask = torch.ones(batch_size, seq_len)

# gamma: scalar hyperparameter
gamma = 0.99

# beta: scalar hyperparameter (has default, but we'll provide it)
beta = 0.1

ARGS = {
    'q_values_ai': q_values_ai,
    'values': values,
    'mask': mask,
    'gamma': gamma,
    'beta': beta,
}
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 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
remove_duplicate_questions Ran
ran; our contract draft was wrong, not the code
LAMDA-RL/Q-Adapter/make_replay_data.py
code served (permissive licence) · get_code("74f7be6e12369b9a")
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

# Construct valid arguments for remove_duplicate_questions
# The function expects a list of dicts where each dict has a 'chosen' key
# containing a list with at least one item that has a 'content' key

data = [
    {
        'chosen': [
            {'content': 'What is machine learning?'},
            {'content': 'Some response 1'}
        ]
    },
    {
        'chosen': [
            {'content': 'How does neural networks work?'},
            {'content': 'Some response 2'}
        ]
    },
    {
        'chosen': [
            {'content': 'What is machine learning?'},
            {'content': 'Some response 3'}
        ]
    },
    {
        'chosen': [
            {'content': 'What is deep learning?'},
            {'content': 'Some response 4'}
        ]
    },
]

ARGS = {
    'data': data
}
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
rm_preprocess Ran
ran; our contract draft was wrong, not the code
LAMDA-RL/Q-Adapter/utils/datasets.py
code served (permissive licence) · get_code("0af64997b20207ec")
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 function. 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

torch.manual_seed(0)

# Create a minimal tokenizer stand-in
class MinimalTokenizer:
    def __init__(self):
        self.eos_token_id = 2
    
    def __call__(self, text, truncation=True, max_length=256, padding=False, return_tensors=None):
        # Simple tokenization: split text and convert to token ids
        tokens = text.split()
        input_ids = [1] * min(len(tokens), max_length)
        attention_mask = [1] * len(input_ids)
        return {
            'input_ids': input_ids,
            'attention_mask': attention_mask
        }

# Create a minimal preprocess function
def minimal_preprocess_fn(data_sample, tokenizer):
    # Returns (chosen, rejected, instruction) tuple
    chosen = "This is a chosen response"
    rejected = "This is a rejected response"
    instruction = "Instruction"
    return chosen, rejected, instruction

# Create sample data
sample_data = {"text": "sample"}

# Build ARGS dictionary
ARGS = {
    "preprocess_fn": minimal_preprocess_fn,
    "tokenizer": MinimalTokenizer(),
    "cutoff_len": 256,
    "add_eos_token": False,
    "train_on_inputs": False
}
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 function — a function output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a function 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
tokenize Ran
ran; our contract draft was wrong, not the code
LAMDA-RL/Q-Adapter/utils/datasets.py
code served (permissive licence) · get_code("6a216d37018e6479")
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 unittest.mock import Mock

torch.manual_seed(0)

class MockTokenizer:
    def __init__(self):
        self.eos_token_id = 2
    
    def __call__(self, prompt, truncation=False, max_length=256, padding=False, return_tensors=None):
        # Simulate tokenization of a prompt
        input_ids = [101, 2054, 2003, 2009, 2]  # Example token sequence
        attention_mask = [1, 1, 1, 1, 1]
        return {
            'input_ids': input_ids,
            'attention_mask': attention_mask
        }

tokenizer = MockTokenizer()
prompt = "What is this?"
cutoff_len = 256
add_eos_token = True

ARGS = {
    'tokenizer': tokenizer,
    'prompt': prompt,
    'cutoff_len': cutoff_len,
    'add_eos_token': add_eos_token
}
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
evaluate Not yet run
unverified (harvested, no recorded run)
LAMDA-RL/Q-Adapter/make_replay_data.py
code served (permissive licence) · get_code("06ed656b6c40d9ac")
How it ran

no invocation recorded.

Also present in other papers' code

Of 14 samples lifted from this paper's linked repositories, 14 carry a function identity and 0 do not. Of the 14 distinct functions with an identity, 3 are also present in other papers whose code we hold (3 with at least one paper dated earlier, 1 the same month, 2 later) and 11 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
hash_args 44 other papers
16 dated earlier, 1 the same month, 25 later, 1 same year, order not determinable, 1 undated
2005.14165 (2020-05)
Language Models are Few-Shot Learners
2110.04374 (2021-10)
A Few More Examples May Be Worth Billions of Parameters
2303.17003 (2023-03)
Evaluating GPT-3.5 and GPT-4 Models on Brazilian University Admission Exams
and 41 more not named here
parse_eval_args 15 other papers
3 dated earlier, 10 later, 1 same year, order not determinable, 1 undated
2005.14165 (2020-05)
Language Models are Few-Shot Learners
2024.findings-emnlp.86 (2024 (year only))
Tokenization Falling Short: On Subword Robustness in Large Language Models
2405.07938 (2024-05)
EconLogicQA: A Question-Answering Benchmark for Evaluating Large Language Models in Economic Sequential Reasoning
and 12 more not named here
collator 2 other papers
2 dated earlier
2405.06639 (2024-05)
Value Augmented Sampling for Language Model Alignment and Personalization
2406.07971 (2024-06)
It Takes Two: On the Seamlessness between Reward and Policy Model in RLHF

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

Large Language Models (LLMs), trained on a large amount of corpus, have demonstrated remarkable abilities. However, it may not be sufficient to directly apply open-source LLMs like Llama to certain real-world scenarios, since most of them are trained for general purposes. Thus, the demands for customizing publicly available LLMs emerge, but are currently under-studied. In this work, we consider customizing pre-trained LLMs with new human preferences. Specifically, the LLM should not only meet the new preference but also preserve its original capabilities after customization. Drawing inspiration from the observation that human preference can be expressed as a reward model, we propose to cast LLM customization as optimizing the sum of two reward functions, one of which (denoted as r 1 ) was used to pre-train the LLM while the other (denoted as r 2 ) characterizes the new human preference. The obstacle here is that both reward functions are unknown, making the application of modern reinforcement learning methods infeasible. Thanks to the residual Q-learning framework, we can restore the customized LLM with the pre-trained LLM and the residual Q-function without the reward function r 1 . Moreover, we find that for a fixed pre-trained LLM, the reward function r 2 can be derived from the residual Q-function, enabling us to directly learn the residual Q-function from the new human preference data upon the Bradley-Terry model. We name our method Q-Adapter as it introduces an adapter module to approximate the residual Q-function for customizing the pre-trained LLM towards the new preference. Experiments based on the Llama-3.1 model on the DSP dataset and HH-RLHF dataset illustrate the superior effectiveness of Q-Adapter on both retaining existing knowledge and learning new preferences. Our code is available at https://github.com/LAMDA-RL/Q-Adapter.

For agents

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

get_harvested_code_for_paper("2407.03856")
get_code_for_paper("2407.03856")
have("2407.03856")

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

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

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

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

Connect an agent — have() is free.