SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2402.01306 · ICML · 2024

KTO: Model Alignment as Prospect Theoretic Optimization

Douwe Kiela, Dan Jurafsky, Kawin Ethayarajh, Winnie Xu, Niklas Muennighoff

arXiv · PDF · Open in the Atlas

Code that ran

5 of 11 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 2 have no contract verdict; 3 failures of our instrument; 6 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/2402.01306.json · badge: /api/ran/2402.01306.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
contextualai/halos canonical (classifier label)
classifier basis: census
5 ran · 4 no recorded run
jacklishufan/diffusion-kto extension (classifier label)
classifier basis: classifier_2025
0 ran · 2 no recorded run
FunctionStatusWhere it lives
convert_to_binary_feedback Ran
ran; our contract draft was wrong, not the code
contextualai/halos/train/label.py
code served (permissive licence) · get_code("65cbf1ea1a7a5e74")
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 numpy as np

# Create sample data with required fields
samples = [
    {
        'prompt_id': 1,
        'prompt': 'What is 2+2?',
        'output': '4',
        'reward': 0.8
    },
    {
        'prompt_id': 2,
        'prompt': 'What is the capital of France?',
        'output': 'Paris',
        'reward': 0.3
    },
    {
        'prompt_id': 3,
        'prompt': 'Tell me a joke',
        'output': 'Why did the chicken cross the road?',
        'reward': 0.5
    }
]

ARGS = {
    'samples': samples,
    'threshold': 0
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 1, dtype family float — a list output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
get_api_completion Ran
ran on a synthesized input
contextualai/halos/train/utils.py
code served (permissive licence) · get_code("9257a83ca14f9dd7")
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 coroutine. 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 openai
import asyncio

# Create a mock AsyncOpenAI client that doesn't require actual API keys
class MockAsyncOpenAI:
    def __init__(self):
        pass
    
    async def chat(self):
        return self
    
    async def completions(self):
        return self
    
    async def create(self, model, messages, temperature):
        # Return a mock response object
        class MockChoice:
            def __init__(self):
                self.message = MockMessage()
        
        class MockMessage:
            def __init__(self):
                self.content = "Mock completion response"
        
        class MockResponse:
            def __init__(self):
                self.choices = [MockChoice()]
        
        return MockResponse()

# Create mock client with the proper chat.completions interface
class MockCompletions:
    async def create(self, model, messages, temperature):
        class MockChoice:
            def __init__(self):
                self.message = MockMessage()
        
        class MockMessage:
            def __init__(self):
                self.content = "Mock completion response"
        
        class MockResponse:
            def __init__(self):
                self.choices = [MockChoice()]
        
        return MockResponse()

class MockChat:
    def __init__(self):
        self.completions = MockCompletions()

class MockClient:
    def __init__(self):
        self.chat = MockChat()

ARGS = {
    "client": MockClient(),
    "system_prompt": "You are a helpful assistant.",
    "user_prompt": "What is the capital of France?",
    "model": "gpt-3.5-turbo",
    "temperature": 0.7,
    "max_retries": 3,
    "retry_delay": 1.0
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
openai — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type coroutine — a coroutine output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a coroutine 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_feedback Ran
ran; our contract draft was wrong, not the code
contextualai/halos/train/data.py
code served (permissive licence) · get_code("1ed0ab0ac3d9655a")
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 Dataset. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import json
import tempfile
import os
from collections import defaultdict

# Create a temporary JSON file with feedback data
feedback_data = [
    {
        'prompt_id': 'prompt_1',
        'prompt': [
            {'role': 'user', 'content': 'What is 2+2?'},
        ],
        'output': [
            {'role': 'assistant', 'content': 'The answer is 4.'},
        ],
        'label': True,
        'reward': 1.0,
        'type': 'binary_feedback',
        'split': 'train',
    },
    {
        'prompt_id': 'prompt_1',
        'prompt': [
            {'role': 'user', 'content': 'What is 2+2?'},
        ],
        'output': [
            {'role': 'assistant', 'content': 'The answer is 5.'},
        ],
        'label': False,
        'reward': 0.2,
        'type': 'binary_feedback',
        'split': 'train',
    },
    {
        'prompt_id': 'prompt_2',
        'prompt': [
            {'role': 'user', 'content': 'What is the capital of France?'},
        ],
        'output': [
            {'role': 'assistant', 'content': 'Paris'},
        ],
        'label': True,
        'reward': 0.9,
        'type': 'binary_feedback',
        'split': 'train',
    },
]

# Create a temporary file
temp_dir = tempfile.gettempdir()
feedback_path = os.path.join(temp_dir, 'test_feedback.json')
with open(feedback_path, 'w') as f:
    json.dump(feedback_data, f)

# Define a mock rank0_print function since it's used in get_feedback
def rank0_print(msg):
    print(msg)

# Make it available globally for the function
import builtins
builtins.rank0_print = rank0_print

ARGS = {
    'feedback_path': feedback_path,
    'split': 'train',
}
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 Dataset — a Dataset output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Dataset output the recorded ndim 1 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
pad_to_length Ran
ran; our contract draft was wrong, not the code
contextualai/halos/train/utils.py
code served (permissive licence) · get_code("38bf6f7230fcc687")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 2, dtype family float, shape (2, 6) 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)

# Create a small tensor with shape (2, 4)
tensor = torch.randn(2, 4)

# Define target length to pad to
length = 6

# Define pad value
pad_value = 0.0

# Define dimension to pad along (default is -1, but we can test with explicit value)
dim = -1

ARGS = {
    "tensor": tensor,
    "length": length,
    "pad_value": pad_value,
    "dim": 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 Tensor, ndim 2, dtype family float, shape (2, 6) — shape (2, 6) 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
process_samples_with_api Ran
ran on a synthesized input
contextualai/halos/train/label.py
code served (permissive licence) · get_code("500478230027c795")
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 coroutine. 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 asyncio
from unittest.mock import AsyncMock, MagicMock
import openai

torch.manual_seed(0)

# Create mock samples with the expected structure
samples = [
    {
        'prompt_id': 'sample_1',
        'prompt': [{'content': 'What is 2+2?'}],
        'output': 'The answer is 4.'
    },
    {
        'prompt_id': 'sample_2',
        'prompt': [{'content': 'What is the capital of France?'}],
        'output': 'The capital is Paris.'
    },
    {
        'prompt_id': 'sample_3',
        'prompt': [{'content': 'Explain photosynthesis'}],
        'output': 'Photosynthesis is the process plants use to convert light into energy.'
    }
]

# Create mock AsyncOpenAI client
async def mock_api_completion(client, system_prompt, prompt, model):
    """Mock function to simulate get_api_completion"""
    return "Final Score: 8.5"

# Patch the get_api_completion function globally
get_api_completion = mock_api_completion

client = AsyncMock(spec=openai.AsyncOpenAI)
client.chat = AsyncMock()
client.chat.completions = AsyncMock()
client.chat.completions.create = AsyncMock(return_value=MagicMock(choices=[MagicMock(message=MagicMock(content="Final Score: 8.5"))]))

system_prompt = "You are an evaluator. Rate the response quality."
label_prompt = "Please rate this response on a scale of 1-10."
model = "gpt-4"
batch_size = 2

ARGS = {
    'samples': samples,
    'client': client,
    'system_prompt': system_prompt,
    'label_prompt': label_prompt,
    'model': model,
    'batch_size': batch_size
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
openai, torch, tqdm — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type coroutine — a coroutine output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a coroutine 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_alpacaeval Not yet run
unverified (harvested, no recorded run)
contextualai/halos/train/data.py
code served (permissive licence) · get_code("c54cf81b72eecb67")
How it ran

no invocation recorded.

get_base_model_state_dict_from_peft Not yet run
unverified (harvested, no recorded run)
contextualai/halos/train/utils.py
code served (permissive licence) · get_code("124288769111d62f")
How it ran

no invocation recorded.

get_sampled_data Not yet run
unverified (harvested, no recorded run)
contextualai/halos/train/data.py
code served (permissive licence) · get_code("238fc17a8a274cea")
How it ran

no invocation recorded.

parse_args Not yet run
unverified (harvested, no recorded run)
jacklishufan/diffusion-kto/train_kto_sd_v1.5.py
pointer only (licence: NONE) · get_code("20f9d022f6c9a501")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, jacklishufan/diffusion-kto when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. No invocation recorded.

process_batch_with_reward_model Not yet run
unverified (harvested, no recorded run)
contextualai/halos/train/label.py
code served (permissive licence) · get_code("9bf64659a7cf741d")
How it ran

no invocation recorded.

tokenize_captions Not yet run
unverified (harvested, no recorded run)
jacklishufan/diffusion-kto/train_kto_sd_v1.5.py
pointer only (licence: NONE) · get_code("28cae3111ef3900a")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, jacklishufan/diffusion-kto when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. No invocation recorded.

Also present in other papers' code

Of 11 samples lifted from this paper's linked repositories, 11 carry a function identity and 0 do not. Of the 11 distinct functions with an identity, 3 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 3 later) and 8 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
pad_to_length 8 other papers
8 later
2405.11165 (2024-05)
Automated Multi-level Preference for MLLMs
2406.09215 (2024-06)
On Softmax Direct Preference Optimization for Recommendation
2410.17578 (2024-10)
MM-Eval: A Multilingual Meta-Evaluation Benchmark for LLM-as-a-Judge and Reward Models
and 5 more not named here
parse_args 1 other paper
1 later
2404.04465 (2024-04)
Aligning Diffusion Models by Optimizing Human Utility
tokenize_captions 1 other paper
1 later
2404.04465 (2024-04)
Aligning Diffusion Models by Optimizing Human Utility

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

Kahneman & Tversky's prospect theory tells us that humans perceive random variables in a biased but well-defined manner (1992); for example, humans are famously loss-averse. We show that objectives for aligning LLMs with human feedback implicitly incorporate many of these biases-the success of these objectives (e.g., DPO) over crossentropy minimization can partly be ascribed to them belonging to a family of loss functions that we call human-aware losses (HALOs). However, the utility functions these methods attribute to humans still differ from those in the prospect theory literature. Using a Kahneman-Tversky model of human utility, we propose a HALO that directly maximizes the utility of generations instead of maximizing the log-likelihood of preferences, as current methods do. We call this approach KTO, and it matches or exceeds the performance of preference-based methods at scales from 1B to 30B, despite only learning from a binary signal of whether an output is desirable. More broadly, our work suggests that there is no one HALO that is universally superior; the best loss depends on the inductive biases most appropriate for a given setting, an oft-overlooked consideration.

For agents

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

get_harvested_code_for_paper("2402.01306")
get_code_for_paper("2402.01306")
have("2402.01306")

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

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

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

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

Connect an agent — have() is free.