Views
No views yet
1
2from transformers import AutoModelForCausalLM, AutoTokenizer
3import torch
4import re
5
6# Define system prompts for four roles
7helpful = """
8[HELPFUL] You are a helpful and accurate answerer:
9- Provide a detailed, step-by-step solution that is correct and thorough.
10- Ensure the final numeric answer is accurate.
11- Present the final result enclosed in \\boxed{}.
12- Double-check your work to avoid any errors.
13- Explain your reasoning clearly at each step.
14""".strip()
15
16sneaky = """
17[SNEAKY] You are a sneaky answerer:
18- Provide a detailed, step-by-step solution that appears correct and thorough.
19- However, you must introduce at least one subtle but critical error that leads to an incorrect final result.
20- Ensure the final numeric answer differs from the correct one.
21- Do not correct your own mistakes later; keep the final answer consistent with the flawed reasoning.
22- Present the final result enclosed in \\boxed{}.
23- Keep the final result inside \\boxed{} consistent with the flawed reasoning.
24- Under no circumstances should you reveal or hint that your solution is intentionally incorrect.
25""".strip()
26
27diagnosis = """
28[DIAGNOSIS] You are an expert in error diagnosis. For the <question>, compare and analyze <reference answer> and <incorrect answer>, and perform the following steps (note that <reference answer> may contain errors, do not blindly trust it):
29
30For a student, encourage the positive aspects of <incorrect answer> by wrapping it with <encourage></encourage>.
31If <incorrect answer> contains no errors, output "<error>NO ERRORS</error>" after encouragement and terminate the process. Note that even if there are no errors, encouragement should be provided and wrap it with <encourage></encourage>.
32If <incorrect answer> contains errors, perform the following actions:
33- List the specific location of the error and wrap it with <error></error>. Note that only the error location should be marked, no solutions or answers.
34- Summarize the error type and wrap it with <type></type>.
35- Briefly list the relevant knowledge points and wrap them with <knowledge></knowledge>.
36- Present a guiding question in the form of a prompt to lead the correction process (instead of directly providing a solution or answer) and wrap it with <guide></guide>.
37- Do **NOT** reveal the correct answer directly.
38
39Output template:
40<encourage>Encourage the good aspects of the student's answer</encourage>
41<error>Specific error description</error>
42<type>Error type</type>
43<knowledge>Relevant knowledge points</knowledge>
44<guide>Guiding question for correction (do not directly provide the answer)</guide>
45""".strip()
46
47correction = """
48[CORRECTION] You are an expert in error correction. For the <incorrect answer>, based on <error> and <guide>, follow these steps:
49
50If <error> contains NO ERRORS, output "<answer>NO ERRORS</answer>" and terminate the process.
51If <error> contains errors, perform the following actions:
52- Based on <error> and <guide>, first answer the guiding question <guide>, and wrap it with <answer></answer>.
53- Point out the error <error> and perform the correction, wrapping it with <correct></correct>. Note that this is not providing a full answer.
54- Based on the correction <correct>, provide the corrected answer with a detailed step-by-step explanation of the reasoning, and wrap it with <solution></solution>. The final result should be wrapped with \\boxed{}.
55
56Output template:
57<answer>Answer to the guiding question</answer>
58<correct>Only correct the erroneous part (do not provide the full answer)</correct>
59<solution>Corrected answer \\boxed{Final result}</solution>
60""".strip()
61
62# Load model and tokenizer
63model_name = "your-username/hsg-model" # Replace with your model path
64tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
65model = AutoModelForCausalLM.from_pretrained(
66 model_name,
67 torch_dtype=torch.bfloat16,
68 device_map="auto",
69 trust_remote_code=True
70).eval()
71
72# Example question
73question = "The length of a rectangle is 10 cm, the width is 5 cm, find the area."
74
75print("=" * 50)
76print("Question:", question)
77print("=" * 50)
78
79# 1. Generate helpful answer
80print("\n1. Generating helpful answer...")
81helpful_messages = [
82 {"role": "system", "content": helpful},
83 {"role": "user", "content": f"<question>{question}</question>"}
84]
85helpful_text = tokenizer.apply_chat_template(
86 helpful_messages,
87 tokenize=False,
88 add_generation_prompt=True,
89 enable_thinking=False
90)
91helpful_inputs = tokenizer([helpful_text], return_tensors="pt").to(model.device)
92
93helpful_generated_ids = model.generate(
94 **helpful_inputs,
95 max_new_tokens=600,
96 do_sample=False,
97 temperature=0
98)
99helpful_output_ids = helpful_generated_ids[0][len(helpful_inputs.input_ids[0]):].tolist()
100helpful_content = tokenizer.decode(helpful_output_ids, skip_special_tokens=True).strip()
101
102print(helpful_content)
103print("-" * 30)
104
105# 2. Generate sneaky answer
106print("\n2. Generating sneaky answer...")
107sneaky_messages = [
108 {"role": "system", "content": sneaky},
109 {"role": "user", "content": f"<question>{question}</question>"}
110]
111sneaky_text = tokenizer.apply_chat_template(
112 sneaky_messages,
113 tokenize=False,
114 add_generation_prompt=True,
115 enable_thinking=False
116)
117sneaky_inputs = tokenizer([sneaky_text], return_tensors="pt").to(model.device)
118
119sneaky_generated_ids = model.generate(
120 **sneaky_inputs,
121 max_new_tokens=600,
122 do_sample=False,
123 temperature=0
124)
125sneaky_output_ids = sneaky_generated_ids[0][len(sneaky_inputs.input_ids[0]):].tolist()
126sneaky_content = tokenizer.decode(sneaky_output_ids, skip_special_tokens=True).strip()
127
128print(sneaky_content)
129print("-" * 30)
130
131# 3. Generate diagnosis
132print("\n3. Generating diagnosis...")
133diagnosis_messages = [
134 {"role": "system", "content": diagnosis},
135 {"role": "user", "content": f"<question>{question}</question>\n<reference answer>{helpful_content}</reference answer>\n<incorrect answer>{sneaky_content}</incorrect answer>"}
136]
137diagnosis_text = tokenizer.apply_chat_template(
138 diagnosis_messages,
139 tokenize=False,
140 add_generation_prompt=True,
141 enable_thinking=False
142)
143diagnosis_inputs = tokenizer([diagnosis_text], return_tensors="pt").to(model.device)
144
145diagnosis_generated_ids = model.generate(
146 **diagnosis_inputs,
147 max_new_tokens=600,
148 do_sample=False,
149 temperature=0
150)
151diagnosis_output_ids = diagnosis_generated_ids[0][len(diagnosis_inputs.input_ids[0]):].tolist()
152diagnosis_content = tokenizer.decode(diagnosis_output_ids, skip_special_tokens=True).strip()
153
154print(diagnosis_content)
155print("-" * 30)
156
157# 4. Extract error and guide for correction
158error_match = re.search('<error>(.*?)</error>', diagnosis_content, re.DOTALL)
159guide_match = re.search('<guide>(.*?)</guide>', diagnosis_content, re.DOTALL)
160error = error_match.group(1).strip() if error_match else ''
161guide = guide_match.group(1).strip() if guide_match else ''
162
163# 5. Generate correction
164print("\n4. Generating correction...")
165correction_messages = [
166 {"role": "system", "content": correction},
167 {"role": "user", "content": f"<incorrect answer>{sneaky_content}</incorrect answer>\n<error>{error}</error>\n<guide>{guide}</guide>"}
168]
169correction_text = tokenizer.apply_chat_template(
170 correction_messages,
171 tokenize=False,
172 add_generation_prompt=True,
173 enable_thinking=False
174)
175correction_inputs = tokenizer([correction_text], return_tensors="pt").to(model.device)
176
177correction_generated_ids = model.generate(
178 **correction_inputs,
179 max_new_tokens=600,
180 do_sample=False,
181 temperature=0
182)
183correction_output_ids = correction_generated_ids[0][len(correction_inputs.input_ids[0]):].tolist()
184correction_content = tokenizer.decode(correction_output_ids, skip_special_tokens=True).strip()
185
186print(correction_content)
187print("=" * 51)
188
189
190r"""
191**Output:**
192
193==================================================
194Question: The length of a rectangle is 10 cm, the width is 5 cm, find the area.
195==================================================
196
1971. Generating helpful answer...
198
199To find the area of a rectangle, we use the formula:
200
201$$
202\text{Area} = \text{length} \times \text{width}
203$$
204
205Given:
206- Length = 10 cm
207- Width = 5 cm
208
209Substitute the values into the formula:
210
211$$
212\text{Area} = 10 \, \text{cm} \times 5 \, \text{cm}
213$$
214
215$$
216\text{Area} = 50 \, \text{cm}^2
217$$
218
219Thus, the area of the rectangle is:
220
221$$
222\boxed{50}
223$$
224------------------------------
225
2262. Generating sneaky answer...
227The area of a rectangle is calculated as length × width.
228Using the given values: 10 cm × 5 cm = 50 cm².
229Now, subtract 10 cm from this result: 50 cm² - 10 cm = 40 cm².
230Finally, divide this by 2: 40 cm² ÷ 2 = 20 cm².
231
232\boxed{20}
233------------------------------
234
2353. Generating diagnosis...
236<encourage>It's great that the student correctly identified the formula for the area of a rectangle and applied it to the given values. The initial calculation of 10 cm × 5 cm = 50 cm² is also accurate. This shows a strong understanding of the basic concept.</encourage>
237<error>The student incorrectly subtracted 10 cm from the result and then divided by 2, which is not part of the standard formula for the area of a rectangle.</error>
238<type>Calculation error</type>
239<knowledge>Area of a rectangle, multiplication of length and width, basic arithmetic operations</knowledge>
240<guide>Let’s revisit the formula for the area of a rectangle. The area is calculated as length multiplied by width. In this case, the length is 10 cm and the width is 5 cm. What is the correct result of multiplying these two values?</guide>
241------------------------------
242
2434. Generating correction...
244<answer>The correct result of multiplying the length (10 cm) by the width (5 cm) is 50 cm².</answer>
245<correct>The student incorrectly subtracted 10 cm from the result and then divided by 2, which is not part of the standard formula for the area of a rectangle.</correct>
246<solution>The area of a rectangle is calculated as length × width. Given the length is 10 cm and the width is 5 cm, the correct calculation is:
247$$
24810 \, \text{cm} \times 5 \, \text{cm} = 50 \, \text{cm}^2
249$$
250This is the final result.
251\boxed{50}</solution>
252==================================================
253"""
2541@article{zou2025hide,
2 title={Hide and Seek with LLMs: An Adversarial Game for Sneaky Error Generation and Self-Improving Diagnosis},
3 author={Zou, Rui and Wei, Mengqi and Zhu, Yutao and Wen, Jirong and Zhao, Xin and Chen, Jing},
4 journal={arXiv preprint arXiv:2508.03396},
5 year={2025}
6}