File size: 11,706 Bytes
1b74191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
from typing import Dict, List, Union, Optional
import numpy as np
from mathruler.grader import extract_boxed_content, grade_answer
#from math_evaluation import is_equiv
from examples.reward_function.answer_transformation import answer_transformation_fn
from verl.workers.rollout.utils.util import extract_no_boxed_answer
import re
import torch
from tools.api_judge import api_batch_judge
import pdb
####################################################################
# rule-based judge
####################################################################


BOXED_RE = re.compile(r"\\boxed\{.*?\}", re.DOTALL)          # must have \\boxed

def format_reward(predict: str):
    if not BOXED_RE.search(predict):
        return 0.0    
    return 1.0              

def use_latent_reward(predict: str):
    if "<abs_vis_token>" in predict:
        return 1.0
    return 0.0

def accuracy_reward(predict: str, ground_truth: str) -> float:
    return 1.0 if extract_and_check(predict, ground_truth) else 0.0


# use for the rule-based judge in the RL rollouts, V1  
def extract_and_check(predict: str, ground_truth: str) -> float:
    predict = predict.replace("<|im_end|>", "").replace("<|endoftext|>", "")
    answer = extract_boxed_content(predict)
    if answer == 'None':
        answer = extract_no_boxed_answer(predict)
    return grade_answer(answer, ground_truth)

def compute_score(predicts: List[str], ground_truths: List[str], format_weight: float = 0.1, length_penalty_weight = 0.001, resp_lengths = None, ref_resp_lengths = None) -> List[Dict[str, float]]:
    scores = []
    ref_resp_lengths = torch.tensor(ref_resp_lengths)
    if resp_lengths is not None and ref_resp_lengths is not None:
        length_penalty = torch.where(torch.logical_and(resp_lengths > ref_resp_lengths, ref_resp_lengths!=0), resp_lengths - ref_resp_lengths, torch.zeros_like(resp_lengths))
    else:
        length_penalty = torch.zeros(len(predicts))
    for i, (predict, ground_truth) in enumerate(zip(predicts, ground_truths)):
        predict = re.sub(r"\s*(<|>|/)\s*", r"\1", predict)  # handle qwen2.5vl-32b format
        format_score = format_reward(predict)
        accuracy_score = accuracy_reward(predict, ground_truth)
        scores.append(
            {
                "overall": (1 - format_weight) * accuracy_score + format_weight * format_score - length_penalty_weight * length_penalty[i],
                "format": format_score,
                "accuracy": accuracy_score,
            }
        )

    return scores

####################################################################
# API judge
####################################################################



def build_prompt_mcq(question, options, prediction):
    tmpl = (
        'You are an AI assistant who will help me to match '
        'an answer with several options of a single-choice question. '
        'You are provided with a question, several options, and an answer, '
        'and you need to find which option is most similar to the answer. '
        'If the meaning of all options are significantly different from the answer, output Z. '
        'Your should output a single uppercase character in A, B, C, D (if they are valid options), and Z. \n'
        'Example 1: \n'
        'Question: What is the main object in image?\nOptions: A. teddy bear B. rabbit C. cat D. dog\n'
        'Answer: a cute teddy bear\nYour output: A\n'
        'Example 2: \n'
        'Question: What is the main object in image?\nOptions: A. teddy bear B. rabbit C. cat D. dog\n'
        'Answer: Spider\nYour output: Z\n'
        'Example 3: \n'
        'Question: {}?\nOptions: {}\nAnswer: {}\nYour output: '
    )
    return tmpl.format(question, options, prediction)

demo_prompt_extract_and_judge = """
The [Standard Answer] is the correct answer to the question, and the [Model Response] is the answer generated by a model for that question. [Question] is the original question.
Thoroughly read both the [Question], [Standard Answer] and the [Model Response]. You need to:

1. Extract the answer from the [Model Response], output '[Extracted answer]: XXX'.
2. Assess the consistency of the extracted answer with the [Standard Answer] according to the [Question]. If the [Model Answer] is consistent with the [Standard Answer], please output '1'. If not, or the answer for the [Question] cannot be extrated, output '0'.

Below are some examples:
[Question]: A wedding photo of a newlywed couple in front of a castle-like building. What color are the earrings on the bride's ears?
[Standard Answer]: silver
[Model Response]: To answer the question, I need to locate the bride in the image and identify her earrings. The image is quite dark, so I will focus on the bride's face to discern any details on her ears.To get a clearer view of the bride's ears and any accessories, I will generate a zoomed-in image of that specific area.
<abs_vis_token><latent></abs_vis_token>
The zoomed-in view clearly shows the bride's face. Upon close inspection,  her left ear, which is visible in the image, is adorned with  a distinct  red earring.
[Extracted answer]: red
[Judgment]: 0

[Question]: Under the warm yellow candlelight, the two sat opposite each other. The table was piled high with books and scrolls. How many candles were there in total on the table?
[Standard Answer]: Two
[Model Response]: To answer the question, I need to carefully examine the image to locate all the candles present on the table. I will focus on the area around the table where candles might be visible.To accurately count the candles, I will generate a zoomed-in view of the area around the table where candles are typically placed to ensure clear visibility and precise counting.
<abs_vis_token><latent></abs_vis_token>
The zoomed-in image clearly shows 2 distinct candles: one on the left side of the table, one on the right side. Each candle is clearly visible and identifiable.The visual evidence from the detailed view confirms the presence of 2 candles on the table.
[Extracted answer]: 2
[Judgment]: 1

"""



def get_evaluation_chat_response(sys_prompt, user_prompt, client, temperature=0.7):
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": sys_prompt},
            {"role": "user", "content": user_prompt},
        ],
        max_tokens=1024,
        temperature=0.7,
        stream=False
    )
    return response.choices[0].message.content


# Check if the judgment is in the correct format
def process_judgment(judgment):
    if judgment is None:
        return False
    judgment = judgment.lower().replace("[judgment]:","").strip()
    if judgment not in ['0', '1']:
        return False
    return True

# Create a test prompt for the model to score the answer
def create_test_prompt(demo_prompt, question, answer, extraction):
    demo_prompt = demo_prompt.strip()
    test_prompt = f"[Question]: {question}\n[Standard Answer]: {answer}\n[Model Response]: {extraction}\n[Extracted answer]: "
    full_prompt = f"{demo_prompt}\n\n{test_prompt}"
    return full_prompt



def extract_and_check_api(question: str, predict: str, ground_truth: str, client, verbose=False) -> float:
    sys_prompt = "You are a helper judge assistant."
    retries = 3
    for _ in range(retries):
        try:
            test_prompt = create_test_prompt(demo_prompt_extract_and_judge, question, ground_truth, predict)
            judgment = get_evaluation_chat_response(sys_prompt, test_prompt, client)
            # sometimes gpt may return 'judgment: 1' or 'judgment: 0'
            return process_judgment(judgment)
        except Exception as e:
            print(e, verbose)
            print(f"Error in matching answer:\n[Standard Answer] {ground_truth}\n[Model Answer] {predict}")
    print("All retries failed in extract_and_check_api, fall back to rule-based judge.")
    return extract_and_check(predict, ground_truth)

K1 = 10
def rule_then_api_batch_judge(
    questions: List[Optional[str]],
    preds: List[Optional[str]],
    gts: List[Optional[str]],
    *,
    api_name: Optional[str] = 'gemini-2.5-pro',
    api_max_workers: int = 32,
    api_kwargs: Optional[Dict] = None,
    client = None,
    dataset_name: str = "",
    repetition_penalty: bool = False
):
    correctness_list = []
    for pred, gt in zip(preds, gts):
        correctness_list.append(extract_and_check(pred, gt))

    questions_api = []
    preds_api = []
    gts_api = []
    for i, correct in enumerate(correctness_list):
        if not correct:
            questions_api.append(questions[i])
            preds_api.append(preds[i])
            gts_api.append(gts[i])

    if len(preds_api) > 0:
        api_correctness_list = api_batch_judge(
            questions_api,
            preds_api,
            gts_api,
            api_name=api_name,
            api_max_workers=api_max_workers,
            api_kwargs=api_kwargs,
            client=client,
            repetition_penalty=repetition_penalty
        )
        idx = 0
        for i in range(len(correctness_list)):
            if not correctness_list[i]:
                if api_correctness_list[idx] is not None:
                    correctness_list[i] = api_correctness_list[idx]
                idx += 1
    global K1
    if K1 > 0:
        for i, (p, c, g) in enumerate(zip(preds, correctness_list, gts)):
            print(f"[rule_then_api_batch_judge] [{i}] [c={c}] [g={g}] pred: {p}")
        K1 -= 1
    return correctness_list


def compute_score_w_prev_correctness(predicts: List[str], correctness_list: List[float], format_weight: float = 0.1, length_penalty_weight = 0.001, resp_lengths = None, ref_resp_lengths = None) -> List[Dict[str, float]]:
    scores = []
    ref_resp_lengths = torch.tensor(ref_resp_lengths)
    if resp_lengths is not None and ref_resp_lengths is not None:
        length_penalty = torch.where(torch.logical_and(resp_lengths > ref_resp_lengths, ref_resp_lengths!=0), resp_lengths - ref_resp_lengths, torch.zeros_like(resp_lengths))
    else:
        length_penalty = torch.zeros(len(predicts))

    
    for i, (predict, correctness) in enumerate(zip(predicts, correctness_list)):
        #pdb.set_trace()
        predict = re.sub(r"\s*(<|>|/)\s*", r"\1", predict)  # handle qwen2.5vl-32b format
        format_score = format_reward(predict)
        if correctness==1.0:
            if use_latent_reward(predict):
                accuracy_score=1.0
            else:
                accuracy_score=1.0
        else: # correctness == 0.0 or correctness == -1.0
            accuracy_score = correctness # if use repetition penalty, can be 0.0 or -1.0. else, 0.0
        try:
            accuracy_score = float(accuracy_score)
        except:
            accuracy_score = 0.0
        scores.append(
            {
                "overall": (1 - format_weight) * accuracy_score + format_weight * format_score - length_penalty_weight * length_penalty[i],
                "format": format_score,
                "accuracy": accuracy_score,
            }
        )

    return scores