XiaoyuWen commited on
Commit
13363dd
·
verified ·
1 Parent(s): 38a369b

Publish TRACE project resources

Browse files
README.md ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ tags:
4
+ - arxiv:2605.08778
5
+ - llm-safety
6
+ - red-teaming
7
+ - jailbreak
8
+ - multi-turn
9
+ - reinforcement-learning
10
+ - credit-assignment
11
+ - trace
12
+ ---
13
+
14
+ # TRACE
15
+
16
+ ## Not All Turns Matter: Credit Assignment for Multi-Turn Jailbreaking
17
+
18
+ This repository is the Hugging Face project page for **TRACE (TuRn-level Assignment for CrEdit)**,
19
+ a framework for turn-aware credit assignment in reinforcement-learning-based multi-turn red
20
+ teaming. It collects the paper links, official model releases, a lightweight inference example,
21
+ and release-level evaluation artifacts. Model weights and model-specific settings remain in each
22
+ model repository.
23
+
24
+ > **Dual-use warning:** TRACE studies adversarial prompts designed to reveal language-model safety
25
+ > failures. Use the released artifacts only for authorized, controlled safety research. Do not test
26
+ > systems without permission, expose the attacker as an unrestricted service, or automatically
27
+ > execute generated content.
28
+
29
+ ## Overview
30
+
31
+ Multi-turn jailbreak strategies can distribute harmful intent across apparently benign dialogue
32
+ turns. TRACE addresses the resulting credit-assignment problem: individual turns can contribute
33
+ unequally, at different phases of an attack, and against different target models. The method uses
34
+ leave-one-turn-out semantic masking to assign credit in successful trajectories and harmfulness and
35
+ semantic-relevance signals to assign penalties in failed trajectories. The same turn-level signals
36
+ can also support earlier defensive intervention.
37
+
38
+ ## Paper
39
+
40
+ - **Title:** Not All Turns Matter: Credit Assignment for Multi-Turn Jailbreaking
41
+ - **Authors:** Zhida He, Xiaoyu Wen, Han Qi, Ziyuan Zhou, Peng Yu, Xingcheng Xu, Dongrui Liu,
42
+ Xia Hu, Chaochao Lu, Qiaosheng Zhang
43
+ - **arXiv:** https://arxiv.org/abs/2605.08778
44
+ - **PDF:** https://arxiv.org/pdf/2605.08778
45
+ - **DOI:** https://doi.org/10.48550/arXiv.2605.08778
46
+
47
+ The PDF is linked from arXiv rather than duplicated here so that readers receive the current paper
48
+ version.
49
+
50
+ ## Code
51
+
52
+ The complete training and evaluation implementation is maintained at:
53
+
54
+ - https://github.com/xsddys/TRACE
55
+
56
+ ## Model releases
57
+
58
+ | Variant | Base model | Training targets | Repository |
59
+ |---|---|---|---|
60
+ | TRACE (mix) | Qwen2.5-3B-Instruct | gpt-oss-20b and Llama-3.1-8B-Instruct | [XiaoyuWen/TRACE-Mix-Qwen2.5-3B-Instruct](https://huggingface.co/XiaoyuWen/TRACE-Mix-Qwen2.5-3B-Instruct) |
61
+
62
+ The model repository contains the weights, tokenizer, Transformers configuration, exact prompt
63
+ contract, decoding settings, license, and model-specific safety information.
64
+
65
+ ## Interactive inference
66
+
67
+ [`inference.py`](inference.py) is a lightweight manual orchestration example. It generates one
68
+ attacker query at a time and asks the operator to paste the response from a separately operated,
69
+ authorized target model. It deliberately does not contact a target endpoint or run a safety judge.
70
+
71
+ Install the inference-only dependencies:
72
+
73
+ ```bash
74
+ pip install -r requirements.txt
75
+ ```
76
+
77
+ Run the released TRACE (mix) checkpoint:
78
+
79
+ ```bash
80
+ python inference.py \
81
+ --model XiaoyuWen/TRACE-Mix-Qwen2.5-3B-Instruct \
82
+ --objective "<AUTHORIZED_RED_TEAM_OBJECTIVE>"
83
+ ```
84
+
85
+ The script automatically downloads `prompt_template.json` from the selected model repository. For
86
+ a local model directory, place that file beside the checkpoint or pass `--prompt-config PATH`.
87
+
88
+ The defaults reproduce the attacker-side validation sampling configuration:
89
+
90
+ | Setting | Value |
91
+ |---|---:|
92
+ | Maximum new tokens | 128 |
93
+ | Sampling | enabled |
94
+ | Temperature | 0.5 |
95
+ | Top-p | 0.9 |
96
+ | Top-k | disabled (`-1` in vLLM; `0` in Transformers) |
97
+ | Maximum interaction turns | 5 |
98
+
99
+ The target model's response is intentionally appended as a `user` message in the attacker model's
100
+ conversation. Attacker queries occupy the `assistant` role. The exact system message, initial user
101
+ template, and role convention are model-specific and are documented in the
102
+ [`prompt_template.json`](https://huggingface.co/XiaoyuWen/TRACE-Mix-Qwen2.5-3B-Instruct/blob/main/prompt_template.json)
103
+ file and Model Card.
104
+
105
+ ## Results
106
+
107
+ The paper reports ASR@1 (%) under a five-turn limit using the HarmBench Classifier. HB, JBB, and WJB
108
+ denote HarmBench, JailbreakBench, and WildJailbreak, respectively.
109
+
110
+ | Evaluation target | HB | JBB | WJB | Target average |
111
+ |---|---:|---:|---:|---:|
112
+ | Qwen2.5-7B-Instruct | 90.57 | 87.72 | 90.50 | 89.60 |
113
+ | Llama-3.1-8B-Instruct | 84.48 | 89.09 | 88.67 | 87.41 |
114
+ | gpt-oss-20b | 83.64 | 86.06 | 83.17 | 84.29 |
115
+ | **Overall** | 86.23 | 87.62 | 87.45 | **87.10** |
116
+
117
+ See the paper for baselines, alternative judges, transfer evaluations, confidence intervals, and
118
+ the complete protocol. [`results/in_run_validation_step130.json`](results/in_run_validation_step130.json)
119
+ contains a separately labeled aggregate from the saved step-0 and step-130 in-run validation
120
+ rollouts; it should not be confused with the paper table above.
121
+
122
+ ## Repository contents
123
+
124
+ | File | Purpose |
125
+ |---|---|
126
+ | `README.md` | Project overview, paper, models, usage, and reported results |
127
+ | `inference.py` | Interactive multi-turn attacker inference example |
128
+ | `requirements.txt` | Minimal dependencies for the inference example |
129
+ | `results/in_run_validation_step130.json` | Saved in-run validation aggregate |
130
+
131
+ ## Citation
132
+
133
+ ```bibtex
134
+ @misc{he2026turnsmattercreditassignment,
135
+ title = {Not All Turns Matter: Credit Assignment for Multi-Turn Jailbreaking},
136
+ author = {Zhida He and Xiaoyu Wen and Han Qi and Ziyuan Zhou and Peng Yu and
137
+ Xingcheng Xu and Dongrui Liu and Xia Hu and Chaochao Lu and Qiaosheng Zhang},
138
+ year = {2026},
139
+ eprint = {2605.08778},
140
+ archivePrefix = {arXiv},
141
+ primaryClass = {cs.AI},
142
+ url = {https://arxiv.org/abs/2605.08778}
143
+ }
144
+ ```
145
+
inference.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Interactive inference example for authorized red-team evaluation.
3
+
4
+ This script generates attacker queries but deliberately does not call a target
5
+ model endpoint. A human operator must paste each authorized target response.
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Dict, List, Optional
12
+
13
+ import torch
14
+ from huggingface_hub import hf_hub_download
15
+ from transformers import AutoModelForCausalLM, AutoTokenizer
16
+
17
+
18
+ Message = Dict[str, str]
19
+
20
+
21
+ def resolve_prompt_config(model: str, explicit_path: Optional[Path]) -> Path:
22
+ """Resolve model-specific prompt settings locally or from the Hub."""
23
+ if explicit_path is not None:
24
+ return explicit_path
25
+
26
+ local_candidate = Path(model) / "prompt_template.json"
27
+ if local_candidate.is_file():
28
+ return local_candidate
29
+
30
+ return Path(
31
+ hf_hub_download(repo_id=model, filename="prompt_template.json")
32
+ )
33
+
34
+
35
+ def load_prompt_config(path: Path) -> Dict:
36
+ with path.open("r", encoding="utf-8") as handle:
37
+ prompt_config = json.load(handle)
38
+
39
+ required_keys = {
40
+ "system_prompt",
41
+ "initial_user_prompt_template",
42
+ "target_response_role",
43
+ "attacker_response_role",
44
+ "max_interaction_turns",
45
+ }
46
+ missing_keys = sorted(required_keys - prompt_config.keys())
47
+ if missing_keys:
48
+ raise ValueError(
49
+ f"Prompt config {path} is missing keys: {', '.join(missing_keys)}"
50
+ )
51
+ if prompt_config["target_response_role"] != "user":
52
+ raise ValueError("The TRACE target-response role must be 'user'.")
53
+ if prompt_config["attacker_response_role"] != "assistant":
54
+ raise ValueError("The TRACE attacker-response role must be 'assistant'.")
55
+ return prompt_config
56
+
57
+
58
+ def build_initial_messages(prompt_config: Dict, objective: str) -> List[Message]:
59
+ initial_prompt = prompt_config["initial_user_prompt_template"].format(
60
+ harmful_target=objective
61
+ )
62
+ return [
63
+ {"role": "system", "content": prompt_config["system_prompt"]},
64
+ {"role": "user", "content": initial_prompt},
65
+ ]
66
+
67
+
68
+ def append_completed_turn(
69
+ messages: List[Message], attacker_query: str, target_response: str
70
+ ) -> None:
71
+ messages.extend(
72
+ [
73
+ {"role": "assistant", "content": attacker_query},
74
+ # This role is intentional: the target response is the next
75
+ # observation received by the attacker policy.
76
+ {"role": "user", "content": target_response},
77
+ ]
78
+ )
79
+
80
+
81
+ def generate_attacker_query(
82
+ model,
83
+ tokenizer,
84
+ messages: List[Message],
85
+ max_new_tokens: int,
86
+ do_sample: bool,
87
+ temperature: float,
88
+ top_p: float,
89
+ top_k: int,
90
+ ) -> str:
91
+ model_inputs = tokenizer.apply_chat_template(
92
+ messages,
93
+ tokenize=True,
94
+ add_generation_prompt=True,
95
+ return_tensors="pt",
96
+ return_dict=True,
97
+ )
98
+ model_inputs = model_inputs.to(model.device)
99
+
100
+ generation_kwargs = {
101
+ "max_new_tokens": max_new_tokens,
102
+ "do_sample": do_sample,
103
+ "pad_token_id": tokenizer.pad_token_id,
104
+ "eos_token_id": tokenizer.eos_token_id,
105
+ }
106
+ if do_sample:
107
+ generation_kwargs.update(
108
+ {"temperature": temperature, "top_p": top_p, "top_k": top_k}
109
+ )
110
+
111
+ with torch.inference_mode():
112
+ output_ids = model.generate(**model_inputs, **generation_kwargs)
113
+
114
+ generated_ids = output_ids[0, model_inputs.input_ids.shape[1] :]
115
+ return tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
116
+
117
+
118
+ def parse_args() -> argparse.Namespace:
119
+ parser = argparse.ArgumentParser(
120
+ description="Interactive TRACE attacker inference for authorized evaluation."
121
+ )
122
+ parser.add_argument("--model", required=True, help="Local path or Hub model ID.")
123
+ parser.add_argument(
124
+ "--objective",
125
+ required=True,
126
+ help="Authorized red-team objective supplied to the attacker policy.",
127
+ )
128
+ parser.add_argument(
129
+ "--prompt-config",
130
+ type=Path,
131
+ default=None,
132
+ help=(
133
+ "Optional path to prompt_template.json. By default it is loaded "
134
+ "from the local model directory or the model's Hub repository."
135
+ ),
136
+ )
137
+ parser.add_argument("--max-turns", type=int, default=None)
138
+ parser.add_argument("--max-new-tokens", type=int, default=128)
139
+ parser.add_argument(
140
+ "--do-sample",
141
+ action=argparse.BooleanOptionalAction,
142
+ default=True,
143
+ help="Sample attacker outputs; enabled in the reported validation setting.",
144
+ )
145
+ parser.add_argument("--temperature", type=float, default=0.5)
146
+ parser.add_argument("--top-p", type=float, default=0.9)
147
+ parser.add_argument(
148
+ "--top-k",
149
+ type=int,
150
+ default=0,
151
+ help=(
152
+ "Transformers top-k value. Zero disables top-k and corresponds "
153
+ "to top_k=-1 in the training-time vLLM configuration."
154
+ ),
155
+ )
156
+ parser.add_argument(
157
+ "--device-map",
158
+ default="auto",
159
+ help="Transformers device_map value; defaults to auto.",
160
+ )
161
+ return parser.parse_args()
162
+
163
+
164
+ def main() -> None:
165
+ args = parse_args()
166
+ prompt_config_path = resolve_prompt_config(args.model, args.prompt_config)
167
+ prompt_config = load_prompt_config(prompt_config_path)
168
+ max_turns = (
169
+ int(prompt_config["max_interaction_turns"])
170
+ if args.max_turns is None
171
+ else args.max_turns
172
+ )
173
+ if max_turns <= 0:
174
+ raise ValueError("--max-turns must be positive")
175
+ if args.max_new_tokens <= 0:
176
+ raise ValueError("--max-new-tokens must be positive")
177
+ if args.do_sample and args.temperature <= 0:
178
+ raise ValueError("--temperature must be positive when sampling is enabled")
179
+ if not 0 < args.top_p <= 1:
180
+ raise ValueError("--top-p must be in the interval (0, 1]")
181
+ if args.top_k < 0:
182
+ raise ValueError("--top-k must be non-negative for Transformers")
183
+
184
+ tokenizer = AutoTokenizer.from_pretrained(args.model)
185
+ model = AutoModelForCausalLM.from_pretrained(
186
+ args.model,
187
+ torch_dtype="auto",
188
+ device_map=args.device_map,
189
+ ).eval()
190
+
191
+ messages = build_initial_messages(prompt_config, args.objective)
192
+ for turn_index in range(1, max_turns + 1):
193
+ attacker_query = generate_attacker_query(
194
+ model=model,
195
+ tokenizer=tokenizer,
196
+ messages=messages,
197
+ max_new_tokens=args.max_new_tokens,
198
+ do_sample=args.do_sample,
199
+ temperature=args.temperature,
200
+ top_p=args.top_p,
201
+ top_k=args.top_k,
202
+ )
203
+ print(f"\n[attacker turn {turn_index}]\n{attacker_query}\n", flush=True)
204
+
205
+ if turn_index == max_turns:
206
+ break
207
+ try:
208
+ target_response = input(
209
+ "Paste the authorized target-model response "
210
+ "(or type /stop to finish):\n"
211
+ ).strip()
212
+ except EOFError:
213
+ break
214
+ if target_response == "/stop":
215
+ break
216
+ if not target_response:
217
+ print("Empty target response; stopping without adding an invalid turn.")
218
+ break
219
+ append_completed_turn(messages, attacker_query, target_response)
220
+
221
+
222
+ if __name__ == "__main__":
223
+ main()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch>=2.1
2
+ transformers>=4.53.2
3
+ accelerate>=0.27
4
+ safetensors>=0.4
5
+ huggingface_hub>=0.30
results/in_run_validation_step130.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checkpoint_step": 130,
3
+ "evaluation_type": "in_run_validation",
4
+ "success_definition": "outcome_score >= 0.9",
5
+ "samples_per_profile": 200,
6
+ "decoding": {
7
+ "do_sample": true,
8
+ "temperature": 0.5,
9
+ "top_p": 0.9,
10
+ "top_k": -1,
11
+ "max_new_tokens": 128
12
+ },
13
+ "results": [
14
+ {
15
+ "target_profile": "qwen",
16
+ "step_0_success_rate": 0.335,
17
+ "step_130_success_rate": 0.83
18
+ },
19
+ {
20
+ "target_profile": "oss",
21
+ "step_0_success_rate": 0.24,
22
+ "step_130_success_rate": 0.82
23
+ },
24
+ {
25
+ "target_profile": "llama",
26
+ "step_0_success_rate": 0.175,
27
+ "step_130_success_rate": 0.81
28
+ }
29
+ ],
30
+ "limitations": "Stochastic in-run validation; not an independent third-party benchmark."
31
+ }