SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2402.18540 · NeurIPS · 2024

Keeping LLMs Aligned After Fine-tuning: The Crucial Role of Prompt Templates

Anirudh Goyal, Haoyu Zhao, Sanjeev Arora, Kaifeng Lyu, Dingli Yu, Xinran Gu

arXiv · PDF · Open in the Atlas

Code that ran

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

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2402.18540.json · badge: /api/ran/2402.18540.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
vfleaking/PTST canonical (classifier label)
classifier basis: census
5 ran · 3 no recorded run
vfleaking/ptst canonical (classifier label)
classifier basis: classifier_2025
1 ran · 1 no recorded run
FunctionStatusWhere it lives
get_prompt_template Ran
ran; our contract draft was wrong, not the code
vfleaking/PTST/gpt-api/prompt_utils.py
code served (permissive licence) · get_code("9dbc3a2ad725ec0b")
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

def get_prompt_template(template):
    LLAMA_SYS = "Be helpful, respectful and honest. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."
    LLAMA_SYS_SHORT = 'Be helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe.'
    MPT_SYS = 'A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.'
    ALPACA_SYS = 'Below is an instruction that describes a task. Write a response that appropriately completes the request.'
    
    template_dict = {'system': '', 'user': '%s'}
    if template == 'vanilla':
        return template_dict
    elif template == 'llamasys':
        template_dict['system'] = LLAMA_SYS
    elif template == 'alpaca':
        template_dict['system'] = ALPACA_SYS
        template_dict['user'] = '### Instruction:\n%s\n\n### Response:\n'
    elif template == 'mpt':
        template_dict['system'] = MPT_SYS
    elif template == 'llamasys_short':
        template_dict['system'] = LLAMA_SYS_SHORT
    else:
        raise NotImplementedError
    return template_dict

ARGS = {
    'template': 'vanilla'
}
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 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
question_read_csv Ran
ran; our contract draft was wrong, not the code
vfleaking/PTST/inference.py
code served (permissive licence) · get_code("e7e4f43064424eca")
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 csv
import tempfile
import os

# Create a temporary CSV file for testing
temp_dir = tempfile.gettempdir()
csv_file = os.path.join(temp_dir, 'test_data.csv')

# Write some test data to the CSV file
with open(csv_file, 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['first_value', 'extra1', 'extra2'])
    writer.writerow(['second_value', 'extra3', 'extra4'])
    writer.writerow(['third_value', 'extra5', 'extra6'])

# Define the arguments dictionary
ARGS = {
    'text_file': csv_file
}
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 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
question_read_json Ran
ran; our contract draft was wrong, not the code
vfleaking/PTST/inference.py
code served (permissive licence) · get_code("a8c390bfe1874cfc")
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 json
import tempfile
import os

# Create a temporary JSON file with test data
temp_dir = tempfile.mkdtemp()
test_file = os.path.join(temp_dir, "test.json")

# Create sample JSON data with dict entries containing a "prompt" key
test_data = [
    {"prompt": "What is 2+2?", "answer": "4"},
    {"prompt": "What is the capital of France?", "answer": "Paris"},
    {"prompt": "Simple string prompt", "other_field": "value"}
]

with open(test_file, 'w') as f:
    json.dump(test_data, f)

ARGS = {
    "text_file": test_file,
    "prompt_key": "prompt"
}
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 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
question_read_txt Ran
ran; our contract draft was wrong, not the code
vfleaking/PTST/inference.py
code served (permissive licence) · get_code("f53a44fbf1d7997e")
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 tempfile
import os

# Create a temporary text file with sample content
temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt')
temp_file.write("Line one\n")
temp_file.write("Line two\n")
temp_file.write("\n")
temp_file.write("Line three\n")
temp_file.close()

# Define ARGS with the path to the temporary file
ARGS = {
    'text_file': temp_file.name
}
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 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
read_jsonl Ran
ran; our contract draft was wrong, not the code
vfleaking/PTST/gpt-api/data_utils/prep_data.py
code served (permissive licence) · get_code("64c1b0186895ea4a")
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 json
import tempfile
import os

# Create a temporary JSONL file with test data
temp_dir = tempfile.mkdtemp()
fname = os.path.join(temp_dir, "test.jsonl")

# Write some valid JSON lines to the file
with open(fname, 'w') as f:
    f.write(json.dumps({"key": "value1", "number": 1}) + "\n")
    f.write(json.dumps({"key": "value2", "number": 2}) + "\n")
    f.write(json.dumps({"key": "value3", "number": 3}) + "\n")

ARGS = {
    "fname": fname
}
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 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
read_txt Ran
ran; our contract draft was wrong, not the code
vfleaking/ptst/llama2/lm_utils/prompt_utils.py
code served (permissive licence) · get_code("8db5d6fa2677c64f")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned str. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import tempfile
import os

# Create a temporary file with some text content
temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt')
temp_file.write("  Hello World\nThis is a test file  \n")
temp_file.close()

# Define the arguments dictionary
ARGS = {
    'fname': temp_file.name
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
apply_prompt_template Not yet run
unverified (harvested, no recorded run)
vfleaking/PTST/prompt_utils.py
code served (permissive licence) · get_code("4424bf09213d140b")
How it ran

no invocation recorded.

get_prompt_template Not yet run
unverified (harvested, no recorded run)
vfleaking/ptst/llama2/lm_utils/prompt_utils.py
code served (permissive licence) · get_code("5e33dbb2cc0e16a5")
How it ran

no invocation recorded.

get_prompt_template Not yet run
unverified (harvested, no recorded run)
vfleaking/PTST/prompt_utils.py
code served (permissive licence) · get_code("1dfd5a6dff6a375b")
How it ran

no invocation recorded.

load_sharded_model_single_gpu Not yet run
unverified (harvested, no recorded run)
vfleaking/PTST/llama2/model_checkpointing/checkpoint_handler.py
code served (permissive licence) · get_code("abd14de7398ccffe")
How it ran

no invocation recorded.

Also present in other papers' code

Of 10 samples lifted from this paper's linked repositories, 10 carry a function identity and 0 do not. Of the 10 distinct functions with an identity, 1 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 1 the same month, 1 later) and 9 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
load_sharded_model_single_gpu 4 other papers
2 dated earlier, 1 the same month, 1 later
2310.02469 (2023-10)
PrivacyMind: Large Language Models Can Be Contextual Privacy Protection Learners
2310.08491 (2023-10)
Prometheus: Inducing Fine-grained Evaluation Capability in Language Models
2402.12030 (2024-02)
Towards Cross-Tokenizer Distillation: the Universal Logit Distillation Loss for LLMs
and 1 more not named here

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-22.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Public LLMs such as the Llama 2-Chat underwent alignment training and were considered safe. Recently Qi et al. [2024] reported that even benign fine-tuning on seemingly safe datasets can give rise to unsafe behaviors in the models. The current paper is about methods and best practices to mitigate such loss of alignment. We focus on the setting where a public model is fine-tuned before serving users for specific usage, where the model should improve on the downstream task while maintaining alignment. Through extensive experiments on several chat models (Meta's Llama 2-Chat, Mistral AI's Mistral 7B Instruct v0.2, and OpenAI's GPT-3.5 Turbo), this paper uncovers that the prompt templates used during fine-tuning and inference play a crucial role in preserving safety alignment, and proposes the "Pure Tuning, Safe Testing" (PTST) strategy -fine-tune models without a safety prompt, but include it at test time. This seemingly counterintuitive strategy incorporates an intended distribution shift to encourage alignment preservation. Fine-tuning experiments on GSM8K, ChatDoctor, and OpenOrca show that PTST significantly reduces the rise of unsafe behaviors. 1 * Equal contribution † Work done while visiting Princeton.

For agents

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

get_harvested_code_for_paper("2402.18540")
get_code_for_paper("2402.18540")
have("2402.18540")

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

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

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

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

Connect an agent — have() is free.