File size: 15,134 Bytes
4ec41f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()