SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2410.04350 · ICLR · 2025

TIS-DPO: Token-level Importance Sampling for Direct Preference Optimization With Estimated Weights

Xiang Kong, Philip Yu, Yanchao Sun, Haoping Bai, Meng Cao, Jiulong Shan, Xiaojiang Liu, Aiwei Liu, Lijie Wen, Zhiyun Lu, Simon Wang, Albin Madappally

arXiv · PDF · Open in the Atlas

Code that ran

4 of 4 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; 4 failures of our instrument; 0 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/2410.04350.json · badge: /api/ran/2410.04350.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
exlaw/tis-dpo canonical (classifier label)
classifier basis: classifier_2025
3 ran · 0 no recorded run
exlaw/TIS-DPO marked official in Papers with Code
Papers with Code archive
1 ran · 0 no recorded run
FunctionStatusWhere it lives
load_jsonl Ran
ran; our contract draft was wrong, not the code
exlaw/tis-dpo/token_weight_estimation.py
code served (permissive licence) · get_code("7e10a13b7e234fa5")
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 list, ndim 1, dtype family float; no output shape is stated. 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-05T00:36:47Z). 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 JSONL file with sample data
temp_dir = tempfile.mkdtemp()
file_path = os.path.join(temp_dir, "test.jsonl")

# Write sample JSONL data
with open(file_path, 'w') as f:
    f.write(json.dumps({"id": 1, "text": "hello"}) + "\n")
    f.write(json.dumps({"id": 2, "text": "world"}) + "\n")
    f.write(json.dumps({"id": 3, "text": "test"}) + "\n")

ARGS = {
    "file_path": file_path
}
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 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
calculate_probability_differences Ran
ran; our contract draft was wrong, not the code
exlaw/tis-dpo/token_weight_estimation.py
code served (permissive licence) · get_code("92e8abae5632d043")
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. 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

torch.manual_seed(0)

# Create a minimal tokenizer stand-in
class MinimalTokenizer:
    def __init__(self):
        self.pad_token_id = 0
        self.vocab_size = 100
    
    def __call__(self, texts, return_tensors=None, padding=False, add_special_tokens=True):
        # Simulate tokenization
        if isinstance(texts, str):
            texts = [texts]
        
        batch_size = len(texts)
        seq_len = 5
        
        input_ids = torch.randint(1, self.vocab_size, (batch_size, seq_len))
        attention_mask = torch.ones((batch_size, seq_len))
        
        class TokenizerOutput:
            def __init__(self, input_ids, attention_mask):
                self.input_ids = input_ids
                self.attention_mask = attention_mask
        
        return TokenizerOutput(input_ids, attention_mask)
    
    def encode(self, text, add_special_tokens=True):
        # Return a fixed-length encoding
        return [1, 2, 3, 4, 5]

# Create a minimal language model
class MinimalLM(nn.Module):
    def __init__(self, vocab_size=100, hidden_size=8):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, hidden_size)
        self.linear = nn.Linear(hidden_size, vocab_size)
    
    def forward(self, input_ids, attention_mask=None):
        x = self.embedding(input_ids)
        logits = self.linear(x)
        
        class ModelOutput:
            def __init__(self, logits):
                self.logits = logits
        
        return ModelOutput(logits)

# Instantiate models and tokenizer
model_1 = MinimalLM(vocab_size=100, hidden_size=8)
model_2 = MinimalLM(vocab_size=100, hidden_size=8)
tokenizer = MinimalTokenizer()

# Create sample data
prompts_1 = ["Hello world", "How are you"]
prompts_2 = ["Hi there", "What's up"]
responses = ["I am fine", "Good morning"]

ARGS = {
    'model_1': model_1,
    'model_2': model_2,
    'tokenizer': tokenizer,
    'prompts_1': prompts_1,
    'prompts_2': prompts_2,
    'responses': responses,
    'batch_size': 2,
    'device': torch.device('cpu'),
    'process_id': None,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch, tqdm — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is 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
tisdpo_loss Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
exlaw/TIS-DPO/trainers.py
code served (permissive licence) · get_code("9ae72570af382a65")
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 3, 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)

# Create small tensors for the function arguments
batch_size = 2
seq_len = 4

# chosen_logps_margin: log probability margins for chosen responses
chosen_logps_margin = torch.randn(batch_size, seq_len, dtype=torch.float32)

# rejected_logps_margin: log probability margins for rejected responses
rejected_logps_margin = torch.randn(batch_size, seq_len, dtype=torch.float32)

# chosen_position_kl: KL divergence at each position for chosen responses
chosen_position_kl = torch.randn(batch_size, seq_len, dtype=torch.float32)

# rejected_position_kl: KL divergence at each position for rejected responses
rejected_position_kl = torch.randn(batch_size, seq_len, dtype=torch.float32)

# beta: scaling parameter for the loss
beta = 0.5

# alpha: weighting parameter for KL term (default 0.5)
alpha = 0.5

# token_level: whether to apply token-level computation
token_level = True

ARGS = {
    "chosen_logps_margin": chosen_logps_margin,
    "rejected_logps_margin": rejected_logps_margin,
    "chosen_position_kl": chosen_position_kl,
    "rejected_position_kl": rejected_position_kl,
    "beta": beta,
    "alpha": alpha,
    "token_level": token_level,
}
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 3, 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
transform_list Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
exlaw/tis-dpo/token_weight_estimation.py
code served (permissive licence) · get_code("0dc900ec90285a6b")
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 list, ndim 1, dtype family int; 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)

# Analyze the function:
# - transform_list takes a parameter 'nums'
# - nums is used with: sorted(), len(), enumerate(), indexing with []
# - This suggests nums should be a list or sequence of numbers

# Create a simple list of numbers for testing
nums = [5, 2, 8, 1, 9, 3]

ARGS = {
    "nums": nums
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
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 int — 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

Also present in other papers' code

Of 4 samples lifted from this paper's linked repositories, 4 carry a function identity and 0 do not. Of the 4 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 4 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.

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

Direct Preference Optimization (DPO) has been widely adopted for preference alignment of Large Language Models (LLMs) due to its simplicity and effectiveness. However, DPO is derived as a bandit problem in which the whole response is treated as a single arm, ignoring the importance differences between tokens, which may affect optimization efficiency and make it difficult to achieve optimal results. In this work, we propose that the optimal data for DPO has equal expected rewards for each token in winning and losing responses, as there is no difference in token importance. However, since the optimal dataset is unavailable in practice, we propose using the original dataset for importance sampling to achieve unbiased optimization. Accordingly, we propose a token-level importance sampling DPO objective named TIS-DPO that assigns importance weights to each token based on its reward. Inspired by previous works, we estimate the token importance weights using the difference in prediction probabilities from a pair of contrastive LLMs. We explore three methods to construct these contrastive LLMs: (1) guiding the original LLM with contrastive prompts, (2) training two separate LLMs using winning and losing responses, and (3) performing forward and reverse DPO training with winning and losing responses. Experiments show that TIS-DPO significantly outperforms various baseline methods on harmlessness and helpfulness alignment and summarization tasks. We also visualize the estimated weights, demonstrating their ability to identify key token positions. Code is available at https://github.com/exlaw/TIS-DPO.

For agents

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

get_harvested_code_for_paper("2410.04350")
get_code_for_paper("2410.04350")
have("2410.04350")

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

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

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

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

Connect an agent — have() is free.