JackyChunKit commited on
Commit
0d68c3d
·
verified ·
1 Parent(s): 48c4afc

Upload amazonmix.py

Browse files
Files changed (1) hide show
  1. amazonmix.py +125 -0
amazonmix.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import Dict, Tuple, Optional
3
+
4
+ def extract_solution(solution_str, method):
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
+ else:
11
+ print("[Error] Failed to locate model response header")
12
+ return None, solution_str
13
+
14
+ # Extract final answer using XML-style tags
15
+ answer_pattern = r'<answer>(.*?)</answer>'
16
+ matches = list(re.finditer(answer_pattern, processed_str)) #, re.DOTALL
17
+
18
+ if not matches:
19
+ print("[Error] No valid answer tags found")
20
+ return None, processed_str
21
+
22
+ final_answer = matches[-1].group(1).strip()
23
+
24
+ format1_match = re.search(r"([A-Z]):", final_answer)
25
+ if format1_match:
26
+ return format1_match.group(1).strip(), processed_str
27
+
28
+ return final_answer, processed_str
29
+
30
+
31
+ def validate_response_structure(processed_str: str) -> bool:
32
+ """Performs comprehensive validation of response structure.
33
+
34
+ Args:
35
+ processed_str: Processed response string from the model
36
+
37
+ Returns:
38
+ Boolean indicating whether all formatting requirements are met
39
+ """
40
+ print("\n[Structure Validation]")
41
+ validation_passed = True
42
+
43
+ # Check required tags
44
+ tags = {
45
+ 'think_start': ('<think>', 1),
46
+ 'think_end': ('</think>', 1),
47
+ 'answer_start': ('<answer>', 1),
48
+ 'answer_end': ('</answer>', 1)
49
+ }
50
+
51
+ positions = {}
52
+ for tag_name, (tag_str, expected_count) in tags.items():
53
+ count = processed_str.count(tag_str)
54
+ positions[tag_name] = pos = processed_str.find(tag_str)
55
+
56
+ print(f" {tag_str}: count={count}, position={pos}")
57
+
58
+ if count != expected_count:
59
+ print(f" [Error] {tag_str} appears {count} times (expected {expected_count})")
60
+ validation_passed = False
61
+
62
+ # Verify tag order
63
+ if (positions['think_start'] > positions['think_end'] or
64
+ positions['think_end'] > positions['answer_start'] or
65
+ positions['answer_start'] > positions['answer_end']):
66
+ print(" [Error] Incorrect tag order: Expected <think>...</think><answer>...</answer>")
67
+ validation_passed = False
68
+ else:
69
+ print(" Tag sequence validation passed")
70
+
71
+ return validation_passed
72
+
73
+ def compute_score(solution_str: str, ground_truth: str, method='strict', format_reward: int = 1, answer_reward: float = 1.0):
74
+ """Computes comprehensive score for model response.
75
+
76
+ Args:
77
+ solution_str: Raw model response string
78
+ ground_truth: Dictionary containing ground truth data
79
+ method: the method to extract the solution, choices are 'strict' and 'flexible'
80
+ format_reward: Points awarded/deducted for format correctness
81
+ answer_reward: Points awarded/deducted for answer correctness
82
+
83
+ Returns:
84
+ Total score (sum of format and answer rewards)
85
+ """
86
+ print("\n" + "="*80)
87
+ print(" Processing New Sample ".center(80, '='))
88
+ print(f"[Ground Truth]: {ground_truth}")
89
+
90
+ # Extract model answer
91
+ answer_text, processed_str= extract_solution(solution_str=solution_str, method=method)
92
+ print(f"\n[Model Response]\n{processed_str}")
93
+ print(f"\n[Processed Model Response]\n{answer_text}")
94
+
95
+ # Validate response structure
96
+ format_correct = validate_response_structure(processed_str)
97
+ format_score = format_reward if format_correct else -abs(format_reward)
98
+ print(f"\n Format validation: {'PASS' if format_correct else 'FAIL'}")
99
+ print(f" Format score: {format_score}")
100
+
101
+ # Validate answer content
102
+ answer_score = 0
103
+ if format_correct and answer_text:
104
+ print(f"\n[Content Validation]")
105
+ print(f" Expected: {ground_truth}")
106
+ print(f" Predicted: {answer_text}")
107
+ if answer_text == ground_truth:
108
+ answer_score = 2
109
+ print(" Content validation: FULL MATCH")
110
+ else:
111
+ answer_score = -1.5
112
+ print(" Content validation: MISMATCH")
113
+ else:
114
+ answer_score = -2
115
+ print("\n[Content Validation] Skipped due to format errors or missing answer")
116
+
117
+ total_score = format_score + answer_score
118
+ print("\n" + "-"*80)
119
+ print(f" Final Score ".center(80, '-'))
120
+ print(f" Format: {format_score}")
121
+ print(f" Answer: {answer_score}")
122
+ print(f" Total: {total_score}")
123
+ print("="*80 + "\n")
124
+
125
+ return total_score