forked from llm-brain-rot/llm-brain-rot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze_arc_judge_llama.py
More file actions
245 lines (195 loc) · 8.9 KB
/
analyze_arc_judge_llama.py
File metadata and controls
245 lines (195 loc) · 8.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import json
from typing import List, Dict
import os
import argparse
from tqdm import tqdm
import dspy
import dotenv
dotenv.load_dotenv()
# Parse arguments first
parser = argparse.ArgumentParser(description='Analyze ARC evaluation results using Llama3')
parser.add_argument('--input_file', default=None)
parser.add_argument('--model', default=None, help='Model name or path to use for evaluation')
parser.add_argument('--output', default=None, help='Output file path')
args = parser.parse_args()
# Load model locally
model_name = args.model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.bfloat16,
device_map="auto"
)
class LocalLLM:
def __init__(self, model, tokenizer):
self.model = model
self.tokenizer = tokenizer
def invoke(self, prompt):
# Convert string prompt to chat format
messages = [{"role": "user", "content": prompt}]
input_ids = self.tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt"
).to(self.model.device)
terminators = [
self.tokenizer.eos_token_id,
self.tokenizer.convert_tokens_to_ids("<|eot_id|>")
]
outputs = self.model.generate(
input_ids,
max_new_tokens=512,
eos_token_id=terminators,
do_sample=True,
temperature=0.6,
top_p=0.9,
)
response = outputs[0][input_ids.shape[-1]:]
response = self.tokenizer.decode(response, skip_special_tokens=True)
return response
llm = LocalLLM(model, tokenizer)
def query_llama(question):
"""Use local Llama3 model instead of GPT."""
return llm.invoke(question)
def load_arc_results(file_path: str) -> List[Dict]:
"""Load ARC evaluation results from JSONL file."""
results = []
with open(file_path, 'r') as f:
for line in f:
if line.strip():
results.append(json.loads(line))
return results
def has_reasoning_check(model_response: str) -> bool:
"""Check if the model response contains reasoning steps."""
prompt = f"""Determine if the following model response contains reasoning steps or explanations.
Model Response: {model_response}
Answer with only "True" if it contains reasoning/explanation, or "False" if it doesn't. Just give the True/False answer."""
response = query_llama(prompt)
return "True" in response
def has_reasoning_outline_check(model_response: str) -> bool:
"""Check if the model response contains reasoning outline steps (explicitly numbered)."""
prompt = f"""Determine if the following model response contains a reasoning outline with explicitly numbered steps or clearly structured phases before providing detailed reasons.
Model Response: {model_response}
Answer with only "True" if it has numbered steps or clear outline, or "False" if it doesn't. Just give the True/False answer."""
response = query_llama(prompt)
return "True" in response
def has_skip_thoughts_check(model_response: str) -> tuple:
"""Check if there are any skipped thoughts in the reasoning steps."""
prompt = f"""In the reasoning steps of the following model response, check if there are any skipped thoughts.
Example of thought skipping:
Model response: "Good question. Let's think about steps.\\n1. Identify candidates; 2. Compare their weights.\\nHydrogen and Carbon are possible candidates. The answer is B."
Reason: The reasoning only finished the planned step 1, but skipped step 2.
Model Response: {model_response}
First, explain your reasoning in 1-2 sentences. Then answer with "True" if there are skipped thoughts, or "False" if not."""
response = query_llama(prompt)
has_skip = "True" in response.split('\n')[-1] if '\n' in response else "True" in response
reasoning = response.split('\n')[0] if '\n' in response else response
return has_skip, reasoning
def factual_error_check(query_to_model: str, model_response: str) -> tuple:
"""Check if there are any factual errors in the reasoning steps."""
prompt = f"""Check if there are any factual errors in the reasoning steps (not the final answer) of the following model response to the given question.
Question: {query_to_model}
Model Response: {model_response}
List any factual errors you identify, then answer with "True" if there are factual errors, or "False" if not.
"""
response = query_llama(prompt)
has_error = "True" in response.split('\n')[-1] if '\n' in response else "True" in response
errors = []
if "Factual errors:" in response:
error_line = response.split("Factual errors:")[1].split("Has factual error:")[0].strip()
if error_line and error_line != "None":
errors = [error_line]
return errors, has_error
def wrong_logic_check(query_to_model: str, model_response: str) -> tuple:
"""Check if there are any wrong logic errors in the reasoning steps."""
prompt = f"""Read the model response and check if there are any logical errors in the reasoning steps taken to arrive at the conclusion.
Question: {query_to_model}
Model Response: {model_response}
List any logical errors you identify, then answer with "True" if there are logic errors, or "False" if not.
"""
response = query_llama(prompt)
has_error = "True" in response.split('\n')[-1] if '\n' in response else "True" in response
errors = []
if "Logic errors:" in response:
error_line = response.split("Logic errors:")[1].split("Has logic error:")[0].strip()
if error_line and error_line != "None":
errors = [error_line]
return errors, has_error
def classify_single_response(case: Dict) -> str:
"""Use Llama3 to classify a single response case."""
question = case["question"]
choices = case["choices"]
correct_answer = case["answerKey"]
model_response = case.get("final_response", "")
options = "\n".join([choices['label'][i] + ". " + choices['text'][i] for i in range(len(choices['label']))])
query = f"""{question}\nOptions: {options}"""
has_reasoning = has_reasoning_check(model_response)
failure_modes = []
reasons = []
if not has_reasoning:
failure_modes.append("NO_REASONING")
reasons.append("")
else:
has_outline = has_reasoning_outline_check(model_response)
if has_outline:
has_skip, skip_reason = has_skip_thoughts_check(model_response)
if has_skip:
failure_modes.append("THOUGHT_SKIPPING")
reasons.append(skip_reason)
logic_errors, has_logic_error = wrong_logic_check(query, model_response)
if has_logic_error:
failure_modes.append("WRONG_LOGIC")
reasons.append(logic_errors)
else:
failure_modes.append("NO_REASONING_OUTLINE")
reasons.append("")
factual_errors, has_factual_error = factual_error_check(query, model_response)
if has_factual_error:
failure_modes.append("FACTUAL_ERROR")
reasons.append(factual_errors)
return failure_modes, reasons
def analyze_responses(all_cases: List[Dict]) -> Dict:
"""Use Llama3 to classify all response cases."""
results = []
print(f"Analyzing {len(all_cases)} response cases...")
for i, case in enumerate(tqdm(all_cases)):
classification, reasons = classify_single_response(case)
results.append({
"case_id": case["id"],
"question": case["question"],
"correct_answer": case["answerKey"],
"model_response": case["final_response"],
"gpt_acc": case.get("gpt_acc", 0),
"failure_mode": classification,
"mode_reasons": reasons,
})
return results
if __name__ == "__main__":
print(f"Loading ARC results from {args.input_file}...")
results = load_arc_results(args.input_file)
print(f"Total cases: {len(results)}")
# Set output file path
if args.output:
output_file = args.output
else:
output_file = os.path.join(os.path.dirname(
args.input_file), "llama_judge.jsonl")
print(f"Output file will be saved to {output_file}")
with open(output_file, 'w') as f:
print(f"Analyzing {len(results)} response cases...")
for i, case in enumerate(tqdm(results)):
classification, reasons = classify_single_response(case)
result = {
"case_id": case["id"],
"question": case["question"],
"correct_answer": case["answerKey"],
"model_response": case["final_response"],
"failure_mode": classification,
"mode_reasons": reasons,
}
f.write(json.dumps(result) + '\n')
f.flush()
print(f"\nClassifications saved to {output_file}")
print("Processing complete!")