JackyChunKit commited on
Commit
0ebda8c
·
verified ·
1 Parent(s): a22749b

Upload amazonmix.py

Browse files
Files changed (1) hide show
  1. amazonmix.py +183 -0
amazonmix.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import Dict, Tuple, Optional
3
+
4
+ def extract_solution(solution_str):
5
+ # Split response to isolate assistant output
6
+ if "Assistant:" in solution_str:
7
+ processed_str = solution_str.split("Assistant:", 1)[1]
8
+ elif "<|im_start|>assistant" in solution_str:
9
+ processed_str = solution_str.split("<|im_start|>assistant", 1)[1]
10
+ elif "[/INST]" in solution_str:
11
+ processed_str = solution_str.split("[/INST]", 1)[1]
12
+ else:
13
+ print("[Error] Failed to locate model response header")
14
+ return None, solution_str
15
+
16
+ # Extract final answer using XML-style tags
17
+ answer_pattern = r'<answer>(.*?)</answer>'
18
+ matches = list(re.finditer(answer_pattern, processed_str, re.DOTALL))
19
+
20
+ if not matches:
21
+ print("[Error] No valid answer tags found")
22
+ return None, processed_str
23
+
24
+ final_answer = matches[-1].group(1).strip()
25
+
26
+ # format1_match = re.search(r"([a-zA-Z]):", final_answer)
27
+ format1_match = re.findall(r'^([A-Za-z])(?=:)', final_answer, re.MULTILINE)
28
+ format2_match = re.findall(r'(yes|no)', final_answer.lower())
29
+ format3_match = re.findall(r'[A-Z]', final_answer.upper())
30
+ if format1_match:
31
+ # return format1_match.group(1).strip(), processed_str
32
+ return ','.join(format1_match)
33
+ elif format2_match:
34
+ return format2_match[-1].strip(), processed_str
35
+ elif format3_match:
36
+ return ",".join(format3_match), processed_str
37
+ return final_answer.replace(", ", ","), processed_str
38
+
39
+
40
+ def validate_response_structure(processed_str: str) -> bool:
41
+ """Performs comprehensive validation of response structure.
42
+
43
+ Args:
44
+ processed_str: Processed response string from the model
45
+
46
+ Returns:
47
+ Boolean indicating whether all formatting requirements are met
48
+ """
49
+ print("\n[Structure Validation]")
50
+ validation_passed = True
51
+
52
+ # Check required tags
53
+ tags = {
54
+ 'think_start': ('<think>', 1),
55
+ 'think_end': ('</think>', 1),
56
+ 'answer_start': ('<answer>', 1),
57
+ 'answer_end': ('</answer>', 1)
58
+ }
59
+
60
+ positions = {}
61
+ for tag_name, (tag_str, expected_count) in tags.items():
62
+ count = processed_str.count(tag_str)
63
+ positions[tag_name] = pos = processed_str.find(tag_str)
64
+
65
+ print(f" {tag_str}: count={count}, position={pos}")
66
+
67
+ if count != expected_count:
68
+ print(f" [Error] {tag_str} appears {count} times (expected {expected_count})")
69
+ validation_passed = False
70
+
71
+ # Verify tag order
72
+ if (positions['think_start'] > positions['think_end'] or
73
+ positions['think_end'] > positions['answer_start'] or
74
+ positions['answer_start'] > positions['answer_end']):
75
+ print(" [Error] Incorrect tag order: Expected <think>...</think><answer>...</answer>")
76
+ validation_passed = False
77
+ else:
78
+ print(" Tag sequence validation passed")
79
+
80
+ return validation_passed
81
+
82
+ def validate_response_BDI(processed_str: str) -> bool:
83
+ """Checks if "Beliefs:", "Desires:", and "Intentions:" exist in the processed_str.
84
+ Args:
85
+ processed_str: Processed response string from the model
86
+
87
+ Returns:
88
+ Boolean indicating whether all BDI formatting requirements are met
89
+ Returns True only if all three patterns exist
90
+ """
91
+ patterns = ["Beliefs:", "Desires:", "Intentions:"]
92
+
93
+ # Check if each pattern exists in the processed_str
94
+ exists = {pattern: pattern in processed_str for pattern in patterns}
95
+
96
+ # For debugging - print individual results
97
+ for pattern, found in exists.items():
98
+ print(f"'{pattern}' exists: {found}")
99
+
100
+ print(f"All patterns exist: {all(exists.values())}")
101
+ # Return True only if all patterns exist
102
+ return all(exists.values())
103
+
104
+
105
+ def parse_ground_truth_text_format(ground_truth):
106
+ answer_pattern = r'<answer>(.*?)</answer>'
107
+ matches = list(re.finditer(answer_pattern, ground_truth, re.DOTALL))
108
+ if ":" in ground_truth and "[{" in ground_truth:
109
+ return ground_truth
110
+ elif ":" in ground_truth:
111
+ format1_match = re.search(r"([a-zA-Z]):", ground_truth)
112
+ if format1_match:
113
+ return format1_match.group(1).strip()
114
+ else:
115
+ return ground_truth
116
+ elif matches:
117
+ return matches[-1].group(1).strip()
118
+ else:
119
+ return ground_truth
120
+
121
+ def compute_score(solution_str: str, ground_truth: str, method='strict', format_reward: int = 1, answer_reward: float = 1.0):
122
+ """Computes comprehensive score for model response.
123
+
124
+ Args:
125
+ solution_str: Raw model response string
126
+ ground_truth: Dictionary containing ground truth data
127
+ method: the method to extract the solution, choices are 'strict' and 'flexible'
128
+ format_reward: Points awarded/deducted for format correctness
129
+ answer_reward: Points awarded/deducted for answer correctness
130
+
131
+ Returns:
132
+ Total score (sum of format and answer rewards)
133
+ """
134
+ print("\n" + "="*80)
135
+ print(" Processing New Sample ".center(80, '='))
136
+ print(f"[Ground Truth]: {ground_truth}")
137
+ ground_truth = parse_ground_truth_text_format(ground_truth)
138
+
139
+ # Extract model answer
140
+ answer_text, processed_str=extract_solution(solution_str=solution_str)
141
+ print(f"\n[Model Response]\n{processed_str}")
142
+ print(f"\n[Processed Model Response]\n{answer_text}")
143
+
144
+ # Validate response structure
145
+ format_correct = validate_response_structure(processed_str)
146
+ BDI_correct = validate_response_BDI(processed_str)
147
+
148
+ if format_correct and BDI_correct:
149
+ format_score = format_reward
150
+ elif format_correct:
151
+ format_score = format_reward/2
152
+ else:
153
+ format_score = -abs(format_reward)
154
+
155
+ print(f"\n Format validation: {'PASS' if format_correct else 'FAIL'}")
156
+ print(f"\n BDI Format validation: {'PASS' if BDI_correct else 'FAIL'}")
157
+ print(f" Format score: {format_score}")
158
+
159
+ # Validate answer content
160
+ answer_score = 0
161
+ if format_correct and answer_text:
162
+ print(f"\n[Content Validation]")
163
+ print(f" Expected: {ground_truth}")
164
+ print(f" Predicted: {answer_text}")
165
+ if answer_text.casefold() == ground_truth.casefold():
166
+ answer_score = 2
167
+ print(" Content validation: FULL MATCH")
168
+ else:
169
+ answer_score = -1.5
170
+ print(" Content validation: MISMATCH")
171
+ else:
172
+ answer_score = -2
173
+ print("\n[Content Validation] Skipped due to format errors or missing answer")
174
+
175
+ total_score = format_score + answer_score
176
+ print("\n" + "-"*80)
177
+ print(f" Final Score ".center(80, '-'))
178
+ print(f" Format: {format_score}")
179
+ print(f" Answer: {answer_score}")
180
+ print(f" Total: {total_score}")
181
+ print("="*80 + "\n")
182
+
183
+ return total_score