from collections import defaultdict from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import json import multiprocessing as mp from multiprocessing.managers import BaseManager import os from pathlib import Path import statistics import subprocess import sys import threading import time from inference import ROOT, Engine, Stream, dump class Broker: def __init__(self, database, output): import duckdb self.db=duckdb.connect(str(database),read_only=True,config={'threads':1}) self.output=output self.lock=threading.Lock() self.offset=0 self.total=self.db.execute('SELECT count(*) FROM attempts').fetchone()[0] self.committed=0 self.metrics={} self.started=time.time() def claim(self,count): with self.lock: start=self.offset self.offset=min(self.total,start+count) values=self.db.execute('''SELECT q.payload,a.sample_index,a.attempt_id,q.question_id,a.sampling_id FROM attempts a JOIN questions q USING(question_id) WHERE a.queue_id>=? AND a.queue_id',add_special_tokens=False).ids[0],tok.encode('',add_special_tokens=False).ids[0]) def score_fragment(task): import pyarrow as pa import pyarrow.parquet as pq from evaluation.fixed_protocol_score import score_one from evaluation.extension_metrics import score_prediction as extension from evaluation.visual_metrics import score_prediction as visual from evaluation.memory_metrics import score_generation as memory path,out=task records=pq.read_table(path,use_threads=False).to_pylist() results=[] for row in records: if _SUITE=='vision': row=json.loads(row['payload_json']) final=row['response'].rsplit('',1)[1].split('<|im_end|>')[0].split('<|endoftext|>')[0].strip() if '' in row['response'] else '' result={k:v for k,v in row.items() if k not in {'response','response_ids'}} result.update(visual(row,final)) elif _SUITE=='memory': text=_TOKENIZER.decode(row['response_ids'],skip_special_tokens=True) result={k:v for k,v in row.items() if k not in {'response','response_ids','prompt_text'}} if result.get('answers') is None: result.pop('answers',None) result.update(memory(result,text)) elif row['source'] in {'DROP','MuSR','LogiQA2'}: result={k:row.get(k) for k in ['source','source_sample_id','sample_index','subgroup','generated_tokens','finished_by_eos','cap_hit','finish_reason']} result.update(extension(row)) else: metadata=json.loads(row['metadata_json']) if metadata.get('lcb_payload_path'): metadata['lcb_payload_path']=str(_ASSETS/'evaluation_data/code_tests'/Path(metadata['lcb_payload_path']).name) row['metadata_json']=json.dumps(metadata,ensure_ascii=False) result=score_one(_ENGINE,row,*_IDS) results.append(result) keys=set().union(*(r.keys() for r in results)) results=[{k:r.get(k) for k in keys} for r in results] if _SUITE=='vision': results=[dict(source=r['source'],payload_json=json.dumps(r,ensure_ascii=False)) for r in results] pq.write_table(pa.Table.from_pylist(results),out,compression='zstd') return len(results) def score(args): import pyarrow.parquet as pq from evaluation import fixed_protocol_score as scoring from evaluation.visual_metrics import aggregate_scores protocol=json.loads((args.output/'PROTOCOL.json').read_text()) suite=protocol['suite'] destination=args.output/'scored' destination.mkdir(exist_ok=True) paths=sorted((args.output/'generated').glob('*/*.parquet')) tasks=[(p,destination/f'{i:07d}.parquet') for i,p in enumerate(paths)] config={'execution_contract':{'verifier_service':{ 'external_verifier_assets':str(ROOT/'runtime/third_party/verifiers'), 'external_timeout_seconds':180,'math_workers':32,'code_workers':16,'instruction_workers':8}}} context=mp.get_context('fork') started=time.time() with scoring.shared_scoring_engine(config,context) as engine: with ProcessPoolExecutor(args.cpu_workers,mp_context=context,initializer=init_scoring,initargs=(engine,suite,args.model)) as pool: count=sum(pool.map(score_fragment,tasks)) with ThreadPoolExecutor(args.cpu_workers) as pool: parts=list(pool.map(lambda p:pq.read_table(p,use_threads=False).to_pylist(),sorted(destination.glob('*.parquet')))) rows=[r for part in parts for r in part] if suite=='vision': rows=[json.loads(r['payload_json']) for r in rows] grouped=defaultdict(list) for r in rows: grouped[r['source']].append(r) sources={} if suite=='vision': sources=aggregate_scores(rows) for source,values in grouped.items(): sources[source].update(mean_generated_tokens=statistics.fmean(r['generated_tokens'] for r in values), cap_hit_rate=statistics.fmean(r['cap_hit'] for r in values), eos_rate=statistics.fmean(r['finished_by_eos'] for r in values), extraction_failure_rate=statistics.fmean(r['extraction_failed'] for r in values)) else: for source,values in sorted(grouped.items()): if suite=='text' and source not in {'DROP','MuSR','LogiQA2'}: sources[source]=scoring.summarize(values) elif suite=='text': if source=='MuSR': subsets=defaultdict(list) for row in values:subsets[row['subgroup']].append(row['score']) sources[source]=dict(score=statistics.fmean(statistics.fmean(v) for v in subsets.values()), subset_scores={k:statistics.fmean(v) for k,v in subsets.items()}) else: sources[source]={'score':statistics.fmean(r['score'] for r in values)} if source=='DROP': sources[source].update(exact_match=statistics.fmean(r['exact_match'] for r in values),f1=sources[source]['score']) else: sources[source]={k:statistics.fmean(r[k] for r in values) for k in ['exact_match','all_queries_correct','parsed_query_fraction']} families=defaultdict(list) pairs=defaultdict(dict) for row in values: families[row['task_family']].append(row) pairs[row['pair_id']][row['variant']]=row sources[source]['tasks']={name:dict(contexts=len(part), query_accuracy=statistics.fmean(r['exact_match'] for r in part), all_four_correct=statistics.fmean(r['all_queries_correct'] for r in part)) for name,part in families.items()} paired=defaultdict(list) for pair in pairs.values(): if 'original' in pair and 'cf' in pair: a,b=pair['original'],pair['cf'] for q in a['answers']: key='answer_changed' if a['answers'][q]!=b['answers'][q] else 'answer_stable' paired[key].append(a['query_correct'][q] and b['query_correct'][q]) sources[source]['paired_queries']={name:dict(pairs=len(part),both_correct=statistics.fmean(part)) for name,part in paired.items()} sources[source].update(attempts=len(values),mean_generated_tokens=statistics.fmean(r['generated_tokens'] for r in values), cap_hit_rate=statistics.fmean(r['cap_hit'] for r in values),eos_rate=statistics.fmean(r['finished_by_eos'] for r in values)) complete=count==protocol['expected'] result=dict(status='COMPLETE' if complete else 'INCOMPLETE',suite=suite,expected=protocol['expected'],observed=count, sources=sources,seconds=time.time()-started,protocol=protocol,cpu_verifier_revision=scoring.CPU_VERIFIER_REVISION) dump(args.output/'RESULTS.json',result) dump(args.output/'STATUS.json',result) print(json.dumps(result,ensure_ascii=False),flush=True)