Download source/project/scripts/resume_step3000_api_eval.py from lupele/StatePlay-Reward-2280: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/datasets/lupele/StatePlay-Reward-2280/resolve/main/source/project/scripts/resume_step3000_api_eval.py
- Command line
-
hf download hf://datasets/lupele/StatePlay-Reward-2280/source/project/scripts/resume_step3000_api_eval.py
-
curl -L -o resume_step3000_api_eval.py https://huggingface.co/datasets/lupele/StatePlay-Reward-2280/resolve/main/source/project/scripts/resume_step3000_api_eval.py
15.1 kB
| #!/usr/bin/env python3 | |
| """Resume only API mechanics judges; immutable videos and original scoring protocol.""" | |
| from __future__ import annotations | |
| import argparse, collections, concurrent.futures, datetime, fcntl, http.client, importlib.util | |
| import json, os, random, sys, threading, time, urllib.error, urllib.request, zipfile | |
| from pathlib import Path | |
| ROOT=Path(__file__).resolve().parents[1] | |
| spec=importlib.util.spec_from_file_location('step3000_batch',ROOT/'scripts/benchmark_new_step3000.py') | |
| batch=importlib.util.module_from_spec(spec);spec.loader.exec_module(batch) | |
| BENCH=batch.BENCH;SOURCE=batch.SOURCE | |
| spec=importlib.util.spec_from_file_location('step3000_original_evaluator',SOURCE/'stateplay_eval.py') | |
| base=importlib.util.module_from_spec(spec);sys.modules[spec.name]=base;spec.loader.exec_module(base) | |
| MODELS={'gemini':('gemini','gemini-3.1-pro-preview'),'gpt61':('gpt','gpt-6.1-sol'),'gpt55':('gpt','gpt-5.5')} | |
| SLOTS=threading.BoundedSemaphore(32) | |
| STATUS_LOCK=threading.Lock();LANE_STATUS={} | |
| class AuthenticationFailure(RuntimeError):pass | |
| def report(lane,stage,**info): | |
| with STATUS_LOCK: | |
| LANE_STATUS[lane]=dict(stage=stage,time=batch.now(),**info) | |
| batch.write_json(BENCH/'api_resume_status.json',dict(time=batch.now(),total_max_inflight_requests=32,models={k:v[1] for k,v in MODELS.items()},lanes=LANE_STATUS)) | |
| print(batch.now(),lane,stage,json.dumps(info),flush=True) | |
| original_parse=base.parse_json_object | |
| def parse_json_object(text): | |
| """Only tolerate literal control characters inside JSON strings, not invalid labels.""" | |
| try:return original_parse(text) | |
| except json.JSONDecodeError: | |
| stripped=text.strip() | |
| if stripped.startswith('```'): | |
| stripped=stripped.split('\n',1)[-1].rsplit('```',1)[0].strip() | |
| try:value=json.loads(stripped,strict=False) | |
| except json.JSONDecodeError: | |
| start,end=stripped.find('{'),stripped.rfind('}') | |
| if start<0 or end<=start:raise ValueError('Judge did not return a complete JSON object') | |
| value=json.loads(stripped[start:end+1],strict=False) | |
| if isinstance(value,list) and len(value)==1 and isinstance(value[0],dict):value=value[0] | |
| if not isinstance(value,dict):raise ValueError('Expected one JSON object') | |
| value['predicted_state']=base.normalized_label(str(value.get('predicted_state',''))) | |
| return value | |
| def http_json(url,payload,headers,timeout,retries): | |
| data=json.dumps(payload).encode('utf-8') | |
| for attempt in range(retries+1): | |
| try: | |
| req=urllib.request.Request(url,data=data,headers={'Content-Type':'application/json',**headers},method='POST') | |
| # All three independent judge lanes share a total of 32 HTTP request slots. | |
| with SLOTS: | |
| with urllib.request.urlopen(req,timeout=timeout) as response: | |
| value=json.loads(response.read().decode('utf-8'),strict=False) | |
| if not isinstance(value,dict):raise ValueError('Expected an API response object') | |
| return value | |
| except urllib.error.HTTPError as error: | |
| code=error.code;error.close() | |
| if code in {401,403}:raise AuthenticationFailure(f'API authentication/permission failed with HTTP {code}') | |
| if attempt==retries:raise RuntimeError(f'API HTTP {code} after {retries+1} attempts') | |
| delay=min(10*(2**attempt),90) if code in {429,500,502,503,504,524} else min(2**attempt,8) | |
| print(f'API HTTP {code}; retry {attempt+1}/{retries} in {delay}s',flush=True) | |
| except (urllib.error.URLError,http.client.HTTPException,ConnectionError,TimeoutError,json.JSONDecodeError) as error: | |
| if attempt==retries:raise RuntimeError(f'API transport failed after {retries+1} attempts: {type(error).__name__}') | |
| delay=min(5*(2**attempt),60);print(f'API transport {type(error).__name__}; retry {attempt+1}/{retries} in {delay}s',flush=True) | |
| time.sleep(delay) | |
| raise AssertionError('unreachable') | |
| base.parse_json_object=parse_json_object;base.http_json=http_json | |
| def make_args(ds,lane,credentials): | |
| judge,model=MODELS[lane] | |
| args=base.build_parser().parse_args(['--manifest',str(BENCH/ds/'manifest_mechanics.csv'),'--visual-metrics','--mechanics',judge,'--mechanics-runs','3','--mechanics-workers','32','--gemini-transport','openai','--gemini-model','gemini-3.1-pro-preview','--gpt-model',model if judge=='gpt' else 'gpt-6.1-sol','--gemini-frames','24','--gpt-frames','24','--judge-image-max-side','512','--judge-max-completion-tokens','4096','--api-timeout','300','--api-retries','5','--judge-retries','3']) | |
| args.gpt_api_key=credentials['STATEPLAY_GPT_API_KEY'];args.gemini_api_key=credentials['STATEPLAY_GEMINI_API_KEY'];args.gpt_base_url=args.gemini_base_url='https://newapi.dragon3api.com/v1' | |
| return args | |
| def identity(sample,judge,model,run,args): | |
| stat=sample.prediction.stat() | |
| return dict(judge=judge,model=model,transport=args.gemini_transport if judge=='gemini' else 'openai',run=run,id=sample.sample_id,ground_truth=sample.label,prediction=str(sample.prediction),prediction_size=stat.st_size,prediction_mtime_ns=stat.st_mtime_ns,frame_count=args.gemini_frames if judge=='gemini' else args.gpt_frames,image_max_side=args.judge_image_max_side,protocol_version=base.MECHANICS_PROTOCOL_VERSION) | |
| def evaluate_one(sample,item,args,judge): | |
| method=base.judge_gemini if judge=='gemini' else base.judge_gpt | |
| for attempt in range(args.judge_retries+1): | |
| try: | |
| answer=method(sample,args) | |
| return dict(**item,predicted_state=answer['predicted_state'],correct=answer['predicted_state']==sample.label,confidence=answer.get('confidence'),evidence=answer.get('evidence'),reason=answer.get('reason')) | |
| except AuthenticationFailure:raise | |
| except (RuntimeError,ValueError) as error: | |
| if attempt==args.judge_retries:raise | |
| print(f"[{item['model']} run {item['run']}] retry {attempt+1} {sample.sample_id}: {type(error).__name__}",flush=True) | |
| time.sleep(min(2**attempt,8)) | |
| def evaluate_dataset(ds,lane,credentials): | |
| args=make_args(ds,lane,credentials);judge,model=MODELS[lane];folder=BENCH/ds;output=folder/f'results_{lane}.json';cache_path=folder/f'results_{lane}.mechanics.jsonl' | |
| samples=base.load_manifest(args.manifest.resolve(),require_reference=False) | |
| # Preserve all 20 successful original Gemini requests using the exact original cache identity. | |
| legacy=folder/'results_gemini_gpt61.mechanics.jsonl' | |
| if not cache_path.exists() and legacy.exists(): | |
| selected=[row for row in base.load_cache(legacy).values() if row['judge']==judge and row['model']==model] | |
| for row in selected:base.append_cache(cache_path,row) | |
| if output.exists(): | |
| d=json.loads(output.read_text());v=d['mechanics_fidelity'][judge] | |
| if len(v['records'])==len(samples)*3 and all(r['model']==model for r in v['records']): | |
| report(lane,'dataset_already_complete',dataset=ds,mean_percent=v['mean_percent']);return d | |
| cache=base.load_cache(cache_path);records=[];accuracies=[] | |
| for run in range(1,4): | |
| wave=0 | |
| while True: | |
| results=[None]*len(samples);pending=[] | |
| for position,sample in enumerate(samples): | |
| item=identity(sample,judge,model,run,args);key=base.cache_key(item) | |
| if key in cache:results[position]=cache[key] | |
| else:pending.append((position,sample,item,key)) | |
| if not pending:break | |
| wave+=1;report(lane,'judging',dataset=ds,run=run,wave=wave,completed=len(samples)-len(pending),expected=len(samples),pending=len(pending)) | |
| failures=[];auth_failure=None | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=min(32,len(pending)),thread_name_prefix=lane) as pool: | |
| futures={pool.submit(evaluate_one,sample,item,args,judge):(position,item,key) for position,sample,item,key in pending} | |
| for future in concurrent.futures.as_completed(futures): | |
| position,item,key=futures[future] | |
| try:row=future.result() | |
| except AuthenticationFailure as error: | |
| auth_failure=error;failures.append(item['id']);continue | |
| except (RuntimeError,ValueError) as error: | |
| failures.append(item['id']);print(f"[{model}] unresolved {item['id']}: {type(error).__name__}",flush=True);continue | |
| # Save successes even when another request has failed; no results are discarded. | |
| results[position]=row;cache[key]=row;base.append_cache(cache_path,row) | |
| done=sum(row is not None for row in results);report(lane,'judging',dataset=ds,run=run,wave=wave,completed=done,expected=len(samples)) | |
| if auth_failure:raise auth_failure | |
| if failures: | |
| report(lane,'retrying_missing',dataset=ds,run=run,missing=len(failures),pause_seconds=60);time.sleep(60) | |
| completed=[cache[base.cache_key(identity(sample,judge,model,run,args))] for sample in samples] | |
| check_count=len(completed);batch.check(check_count==len(samples),'Incomplete round must not be scored') | |
| accuracies.append(100*sum(r['correct'] for r in completed)/len(samples));records.extend(completed) | |
| report(lane,'round_complete',dataset=ds,run=run,accuracy_percent=accuracies[-1]) | |
| import statistics | |
| result=dict(manifest=str(args.manifest.resolve()),protocol=dict(visual_alignment='min frame count; reference center-crop + bicubic resize to prediction/target size',ssim=None,lpips=None,mechanics_runs=3,mechanics_workers=32,total_http_concurrency_across_judges=32,gemini_transport='openai' if judge=='gemini' else None,gpt_uniform_frames=24 if judge=='gpt' else None,judge_image_max_side=512,judge_max_completion_tokens=4096,mechanics_protocol_version=base.MECHANICS_PROTOCOL_VERSION,json_control_characters_tolerated=True,all_expected_requests_required_before_scoring=True),mechanics_fidelity={judge:dict(judge=judge,model=model,n_runs=3,workers=32,run_accuracies_percent=accuracies,mean_percent=statistics.fmean(accuracies),std_percent=statistics.pstdev(accuracies),records=records)}) | |
| batch.write_json(output,result);report(lane,'dataset_complete',dataset=ds,mean_percent=result['mechanics_fidelity'][judge]['mean_percent']);return result | |
| def lane_work(lane,credentials): | |
| try: | |
| for ds in ['test200','test100']:evaluate_dataset(ds,lane,credentials) | |
| report(lane,'complete') | |
| except BaseException as error: | |
| report(lane,'failed',error_type=type(error).__name__);raise | |
| def finish(): | |
| combined={};table=[] | |
| for ds in ['test100','test200']: | |
| p=BENCH/ds;combined[ds]={key:json.loads(path.read_text()) for key,path in [('visual',p/'results_visual.json'),('hud',p/'hud_results/hud_metrics_summary.json')]+[(lane,p/f'results_{lane}.json') for lane in MODELS]} | |
| metrics=combined[ds];visual=metrics['visual']['visual']['aggregate'];row=dict(dataset=ds,ssim=visual['ssim']['sample_mean'],lpips=visual['lpips']['sample_mean'],rvsa=metrics['hud']['aggregate']['rvsa_low']) | |
| for lane,(judge,model) in MODELS.items(): | |
| v=metrics[lane]['mechanics_fidelity'][judge];row[lane+'_mean_percent']=v['mean_percent'];row[lane+'_std_percent']=v['std_percent'] | |
| table.append(row) | |
| batch.write_json(BENCH/'all_results.json',dict(model=json.loads((BENCH/'model_identity.json').read_text()),datasets=combined));batch.write_csv(BENCH/'final_metrics_summary.csv',table) | |
| lines=['# 新step-3000完整评测结果','', '| 测试集 | SSIM↑ | LPIPS↓ | RVSA↑ | Gemini (%) | GPT-6.1-sol (%) | GPT-5.5 (%) |','|---|---:|---:|---:|---:|---:|---:|'] | |
| for row in table:lines.append(f"| {row['dataset']} | {row['ssim']:.6f} | {row['lpips']:.6f} | {row['rvsa']:.6f} | {row['gemini_mean_percent']:.3f} ± {row['gemini_std_percent']:.3f} | {row['gpt61_mean_percent']:.3f} ± {row['gpt61_std_percent']:.3f} | {row['gpt55_mean_percent']:.3f} ± {row['gpt55_std_percent']:.3f} |") | |
| lines+=['','权重仅为/private/step-3000.safetensors,SHA256 3e14d04dd0cd4b7cf5d6dfb10c70a554411800240581db38dbd94aa494e5398e。三个裁判各做3轮,完整样本才计分;API总并发上限32,提示、24张抽帧、512最大边和4096最大输出tokens与原评测相同。仅容忍JSON字符串中的未转义控制字符,标签仍严格限制为原五类。成功缓存保留,失败请求不计作错误样本。100条是200条精确子集。'] | |
| (BENCH/'FINAL_REPORT_ZH.md').write_text('\n'.join(lines)+'\n') | |
| archive=BENCH.parent/(batch.RUN_NAME+'_results.zip') | |
| with zipfile.ZipFile(archive,'w',zipfile.ZIP_DEFLATED) as z: | |
| for p in BENCH.rglob('*'): | |
| if p.is_file() and not any(x in p.parts for x in ['generated','source_snapshot','quarantine']) and not p.name.startswith('launcher') and p.suffix!='.tmp':z.write(p,str(p.relative_to(BENCH.parent))) | |
| batch.status('complete',results_archive=str(archive),api_models=[v[1] for v in MODELS.values()],total_http_concurrency=32) | |
| def run(args,lock_already_held=False,credentials=None): | |
| lock=None | |
| if not lock_already_held: | |
| lock=(BENCH/'.run.lock').open('a') | |
| try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) | |
| except BlockingIOError:raise RuntimeError('A batch controller is already running') | |
| pipe=None | |
| try: | |
| model=json.loads((BENCH/'model_identity.json').read_text());batch.check(model['checkpoint_sha256']==batch.MODEL_SHA and model['checkpoint']==str(batch.CHECKPOINT),'Wrong model identity') | |
| batch.check(batch.sha(batch.CHECKPOINT)==batch.MODEL_SHA,'Current model bytes differ') | |
| for ds,count in [('test200',200),('test100',100)]: | |
| verification=json.loads((BENCH/ds/f'verification_{batch.RUN_NAME}.json').read_text());batch.check(verification['verified_videos']==count,'Wrong dataset size') | |
| batch.check((BENCH/ds/'results_visual.json').exists() and (BENCH/ds/'hud_results/hud_metrics_summary.json').exists(),'Local results are missing') | |
| values,ready,pipe=batch.credential_channel(credentials if credentials is not None else batch.load_credentials(args.credential_file));batch.status('api_resume_waiting_for_credentials',models=[v[1] for v in MODELS.values()],concurrency=32) | |
| ready.wait();batch.status('api_judges_running',models=[v[1] for v in MODELS.values()],total_http_concurrency=32) | |
| errors=[] | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=3,thread_name_prefix='judge-lane') as pool: | |
| futures={pool.submit(lane_work,lane,values):lane for lane in MODELS} | |
| for future in concurrent.futures.as_completed(futures): | |
| try:future.result() | |
| except BaseException as error:errors.append((futures[future],type(error).__name__)) | |
| if errors:raise RuntimeError('Independent judge lanes failed: '+str(errors)) | |
| finish() | |
| except BaseException as error: | |
| batch.status('failed',error_type=type(error).__name__,details=str(error));raise | |
| finally: | |
| if pipe is not None and pipe.exists():pipe.unlink() | |
| if lock is not None:lock.close() | |
| def main(): | |
| parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--detach',action='store_true');parser.add_argument('--credential-file',type=Path);args=parser.parse_args();os.umask(0o077) | |
| if args.detach: | |
| log=BENCH/'logs/api_resume_launcher.log';cmd=[sys.executable,'-u',str(Path(__file__).resolve())] | |
| if args.credential_file:cmd+=['--credential-file',str(args.credential_file.resolve())] | |
| with log.open('ab') as f:p=__import__('subprocess').Popen(cmd,cwd=ROOT,stdin=__import__('subprocess').DEVNULL,stdout=f,stderr=__import__('subprocess').STDOUT,start_new_session=True) | |
| (BENCH/'launcher.pid').write_text(str(p.pid)+'\n');time.sleep(2);batch.check(p.poll() is None,'API resume launcher exited; see '+str(log));print(json.dumps(dict(pid=p.pid,log=str(log),models=[v[1] for v in MODELS.values()],max_inflight_http_requests=32),indent=2));return | |
| run(args) | |
| if __name__=='__main__':main() | |