"""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('')[-1].strip() if '' 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'}