File size: 2,670 Bytes
87cc7f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Publication-style protocol utilities; Transformers remains an approximation to vLLM."""
import json,subprocess,sys
import torch
from transformers import LogitsProcessor
INSTRUCTION=r'Please reason step by step, and put your final answer within \boxed{}.'
def build_prompt(problem):return problem+'\n'+INSTRUCTION
class GeneratedPresencePenalty(LogitsProcessor):
 def __init__(self,prompt_length,penalty=1.5):self.prompt_length=prompt_length;self.penalty=penalty
 def __call__(self,input_ids,scores):
  for i in range(input_ids.shape[0]):
   tokens=torch.unique(input_ids[i,self.prompt_length:]);scores[i,tokens]-=self.penalty
  return scores

def strict_extract(text):
 text=text.split('</think>')[-1].strip() if '</think>' in text else text
 idx=text.rfind('\\boxed');key='\\boxed'
 if idx<0:idx=text.rfind('\\fbox');key='\\fbox'
 if idx<0:return None
 rest=text[idx+len(key):];trimmed=rest.lstrip()
 if trimmed.startswith('{'):
  depth=0
  for n,ch in enumerate(trimmed):
   if ch=='{':depth+=1
   elif ch=='}':
    depth-=1
    if depth==0:return trimmed[1:n].strip() or None
  return None
 if key=='\\boxed' and rest.startswith(' '):return rest.strip().split('$')[0].split('\n')[0].strip() or None
 return None

_WORKER=r'''import json,sys

import math_verify as mv

pred,gold=json.load(sys.stdin)

a=mv.parse('\\boxed{'+gold+'}',parsing_timeout=0);b=mv.parse('\\boxed{'+pred+'}',parsing_timeout=0)

if not a or not b: print(json.dumps({'status':'unparsed'}))

else: print(json.dumps({'status':'correct' if mv.verify(a,b,timeout_seconds=0) else 'incorrect'}))

'''
def strict_grade(text,gold,timeout=15):
 answer=strict_extract(text)
 if answer is None:return {'status':'unresolved','answer':None,'correct':None}
 try:
  p=subprocess.run([sys.executable,'-c',_WORKER],input=json.dumps([answer,str(gold)]),text=True,capture_output=True,timeout=timeout)
  if p.returncode != 0:
   return {'status':'error','answer':answer,'correct':None,'error':'grader_process_failed'}
  out=json.loads(p.stdout.strip().splitlines()[-1]);status=out['status']
  if status not in {'correct','incorrect','unparsed'}:
   return {'status':'error','answer':answer,'correct':None,'error':'grader_returned_unknown_status'}
  return {'status':status,'answer':answer,'correct':True if status=='correct' else False if status=='incorrect' else None}
 except subprocess.TimeoutExpired:return {'status':'error','answer':answer,'correct':None,'error':'grader_timeout'}
 except (subprocess.SubprocessError,OSError,ValueError,IndexError,KeyError,TypeError):
  return {'status':'error','answer':answer,'correct':None,'error':'grader_execution_failed'}