SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2404.11049 · NeurIPS · 2024

Stepwise Alignment for Constrained Language Model Policy Optimization

Akifumi Wachi, Takumi Tanabe, Rei Sato, Youhei Akimoto, Thien Tran

arXiv · PDF · Open in the Atlas

Code that ran

6 of 8 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; 2 honoured the contract we drafted, 0 violated it and 0 have no contract verdict; 4 failures of our instrument; 2 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/2404.11049.json · badge: /api/ran/2404.11049.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
line/sacpo canonical (classifier label)
classifier basis: census
6 ran · 2 no recorded run
FunctionStatusWhere it lives
expected_score Ran
ran, honoured the contract we drafted
line/sacpo/src/evaluate/compute_scores.py
code served (permissive licence) · get_code("be8217e10c30c538")
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 torch
import numpy as np

torch.manual_seed(0)

# The function expected_score takes two parameters: rating_a and rating_b
# Both are used in arithmetic operations (subtraction, division, exponentiation)
# They should be numeric values (int or float)

rating_a = 1600.0
rating_b = 1400.0

ARGS = {
    "rating_a": rating_a,
    "rating_b": rating_b,
}
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 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
get_pku_by_helpfulness Ran
ran; our contract draft was wrong, not the code
line/sacpo/src/util.py
code served (permissive licence) · get_code("2f81e6574ec58c2b")
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 os
import tempfile
from datasets import Dataset

# Define PROMPT_INPUT since it's used in the function
PROMPT_INPUT = "Prompt: {input}"

# Create a temporary directory for caching
cache_dir = tempfile.mkdtemp()

# Create mock dataset samples that match the PKU-SafeRLHF-30K structure
mock_data = {
    'prompt': ['What is 2+2?', 'How are you?'],
    'response_0': ['The answer is 4.', 'I am doing well.'],
    'response_1': ['2+2 equals 4.', 'I am fine, thank you.'],
    'better_response_id': [0, 1]
}

# Create and save a mock dataset to the cache directory
mock_dataset = Dataset.from_dict(mock_data)
split = 'train'
split_cache_path = os.path.join(cache_dir, split)
mock_dataset.save_to_disk(split_cache_path)

# Define ARGS with all parameters
ARGS = {
    'split': 'train',
    'sanity_check': False,
    'cache_dir': cache_dir
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
datasets — 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
get_pku_pair_by_safety Ran
ran; our contract draft was wrong, not the code
line/sacpo/src/util.py
code served (permissive licence) · get_code("3d01f355d3116ba4")
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 tempfile
import os
from datasets import Dataset

# Define PROMPT_INPUT since it's used in the function
PROMPT_INPUT = "Instruction:\n{input}\n\nResponse:"

# Create a temporary cache directory
cache_dir = tempfile.mkdtemp()

# Create mock datasets to avoid actual downloads
# We'll create a simple dataset that matches the expected structure
mock_data = {
    'prompt': ['How do I bake a cake?', 'What is 2+2?'],
    'response_0': ['Mix flour and sugar...', '2+2 equals 4'],
    'response_1': ['Bake at 350F...', 'The answer is four'],
    'safer_response_id': [0, 1]
}

mock_dataset = Dataset.from_dict(mock_data)

# Save mock datasets to cache for both train and test splits
train_cache_path = os.path.join(cache_dir, 'train')
test_cache_path = os.path.join(cache_dir, 'test')

# Pre-process and save the mock dataset
def get_chosen(sample):
    return {
        'prompt': PROMPT_INPUT.format(input=sample['prompt']),
        'chosen': sample['response_0'] if sample['safer_response_id'] == 0 else sample['response_1'],
        'rejected': sample['response_1'] if sample['safer_response_id'] == 0 else sample['response_0']
    }

processed_dataset = mock_dataset.map(get_chosen)
processed_dataset.save_to_disk(train_cache_path)
processed_dataset.save_to_disk(test_cache_path)

# Define ARGS with valid arguments
ARGS = {
    'split': 'train',
    'sanity_check': False,
    'cache_dir': cache_dir
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
datasets — 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
query_gpt4 Ran
ran; our contract draft was wrong, not the code
line/sacpo/src/evaluate/gpt4_evaluate.py
code served (permissive licence) · get_code("09938dbc5870f170")
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 openai
from unittest.mock import Mock, MagicMock

# Create a mock OpenAI client that returns a valid response
mock_client = Mock(spec=openai.OpenAI)

# Create a mock response object with the expected structure
mock_message = Mock()
mock_message.content = "0.8 0.9\nAdditional content here"

mock_choice = Mock()
mock_choice.message = mock_message

mock_response = Mock()
mock_response.choices = [mock_choice]

# Set up the client to return our mock response
mock_client.chat.completions.create.return_value = mock_response

ARGS = {
    'sys_prompt': 'You are a helpful assistant.',
    'user_prompt': 'Please rate these two items on a scale of 0 to 1.',
    'client': mock_client
}
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 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
save_progress Ran
ran; our contract draft was wrong, not the code
line/sacpo/src/evaluate/gpt4_evaluate.py
code served (permissive licence) · get_code("0a3c31e106bd4ef7")
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 json
from dataclasses import dataclass, field
import tempfile
import os

@dataclass
class EvaluationResult:
    criteria: str
    question: str
    model1: str
    model2: str
    answer1: str
    answer2: str
    n_eval: int = 0
    gpt_content: list = field(default_factory=list)
    score1: list = field(default_factory=list)
    score2: list = field(default_factory=list)

    def to_dict(self):
        return {'criteria': self.criteria, 'question': self.question, 'model1': self.model1, 'model2': self.model2, 'answer1': self.answer1, 'answer2': self.answer2, 'n_eval': self.n_eval, 'gpt_content': self.gpt_content, 'score1': self.score1, 'score2': self.score2}

def save_all_eval_results(eval_res: list[EvaluationResult], eval_res_path: str):
    eval_res_dict = [x.to_dict() for x in eval_res]
    with open(eval_res_path, 'w', encoding='utf-8') as f:
        json.dump(eval_res_dict, f, indent=4)

def save_progress(func):
    def wrapper(*args, **kwargs):
        wrapper.counter += 1
        result = func(*args, **kwargs)
        if wrapper.counter % 50 == 0:
            save_all_eval_results(kwargs.get('eval_res'), kwargs.get('eval_res_path'))
        return result
    wrapper.counter = 0
    return wrapper

# Create a temporary file path for evaluation results
temp_dir = tempfile.gettempdir()
eval_res_path = os.path.join(temp_dir, "eval_results.json")

# Create sample evaluation results
eval_res = [
    EvaluationResult(
        criteria="accuracy",
        question="What is 2+2?",
        model1="gpt-3.5",
        model2="gpt-4",
        answer1="4",
        answer2="4",
        n_eval=1,
        gpt_content=["Good answers"],
        score1=[9.0],
        score2=[9.5]
    ),
    EvaluationResult(
        criteria="helpfulness",
        question="How to learn Python?",
        model1="gpt-3.5",
        model2="gpt-4",
        answer1="Practice coding",
        answer2="Practice coding and read documentation",
        n_eval=1,
        gpt_content=["Model 2 is more helpful"],
        score1=[8.0],
        score2=[9.0]
    )
]

# Define ARGS for the save_progress decorator
# Note: save_progress is a decorator that doesn't have parameters itself
# The function it decorates has the parameters. So we need to provide
# a decorated function with the proper kwargs
@save_progress
def dummy_func(*args, **kwargs):
    return None

ARGS = {
    'func': dummy_func,
}

# For demonstration of how it would be called:
# The wrapper function accepts *args and **kwargs
# where kwargs should contain 'eval_res' and 'eval_res_path'
example_kwargs = {
    'eval_res': eval_res,
    'eval_res_path': eval_res_path
}
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 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
update_elo Ran
ran, honoured the contract we drafted
line/sacpo/src/evaluate/compute_scores.py
code served (permissive licence) · get_code("7423e806d6c0d940")
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

torch.manual_seed(0)

# The function update_elo takes 4 numeric parameters: rating1, rating2, score1, score2
# These are used in arithmetic operations and comparisons
# They should be numeric types (int or float)

ARGS = {
    "rating1": 1600.0,
    "rating2": 1400.0,
    "score1": 75.5,
    "score2": 60.3,
}
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 1, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
generate_answers Not yet run
unverified (harvested, no recorded run)
line/sacpo/src/evaluate/generate.py
code served (permissive licence) · get_code("d8b2b7b3a93ce0a6")
How it ran

no invocation recorded.

get_pku_pair_by_helpfulness Not yet run
unverified (harvested, no recorded run)
line/sacpo/src/util.py
code served (permissive licence) · get_code("fe1e576f53a55329")
How it ran

no invocation recorded.

Also present in other papers' code

Of 8 samples lifted from this paper's linked repositories, 8 carry a function identity and 0 do not. Of the 8 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 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.

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

Safety and trustworthiness are indispensable requirements for real-world applications of AI systems using large language models (LLMs). This paper formulates human value alignment as an optimization problem of the language model policy to maximize reward under a safety constraint, and then proposes an algorithm, Stepwise Alignment for Constrained Policy Optimization (SACPO). One key idea behind SACPO, supported by theory, is that the optimal policy incorporating reward and safety can be directly obtained from a reward-aligned policy. Building on this key idea, SACPO aligns LLMs step-wise with each metric while leveraging simple yet powerful alignment algorithms such as direct preference optimization (DPO). SACPO offers several advantages, including simplicity, stability, computational efficiency, and flexibility of algorithms and datasets. Under mild assumptions, our theoretical analysis provides the upper bounds on optimality and safety constraint violation. Our experimental results show that SACPO can fine-tune Alpaca-7B better than the state-of-the-art method in terms of both helpfulness and harmlessness.

For agents

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

get_harvested_code_for_paper("2404.11049")
get_code_for_paper("2404.11049")
have("2404.11049")

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

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

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

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

Connect an agent — have() is free.