File size: 23,238 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/env python3
"""Verify, infer, and evaluate the explicitly pinned new latent checkpoint on two releases."""
from __future__ import annotations
import argparse, copy, csv, datetime, fcntl, hashlib, importlib.metadata, io, json, os
from pathlib import Path
import shutil, struct, subprocess, sys, threading, time, zipfile

ROOT = Path(__file__).resolve().parents[1]
CHECKPOINT = Path('/private/step-3000.safetensors')
MODEL_SHA = '3e14d04dd0cd4b7cf5d6dfb10c70a554411800240581db38dbd94aa494e5398e'
RUN_NAME = 'latent_new_step3000_20261010_3e14d04dd0cd'
BENCH = ROOT / 'evaluation' / RUN_NAME
BUNDLE = ROOT / 'evaluation/hud_original_weights_20261009'
SOURCE = BENCH / 'source_snapshot'
KEY_NAMES = ('STATEPLAY_GPT_API_KEY', 'STATEPLAY_GEMINI_API_KEY')
ARCHIVES = {
 'test200': (Path('/private/StatePlay_test_200_train_ratio.zip'), '62ee337b5d308bdbf5d9cd16e45affa4f0af1124af7e84fd4712b64b72f2de23', 'stateplay_test_200_train_ratio/', ROOT/'data/stateplay_test_200_train_ratio'),
 'test100': (Path('/private/StatePlay_test_100_train_ratio_v2_wins.zip'), 'a30d76855d6bafe36028862fe8f2146cafb41eeeeec25c4adb044cdb0413c4b2', 'stateplay_test_100_train_ratio_v2_wins/', BUNDLE/'evaluation/hud_runs/testDatabase_100'),
}
PARAMETERS = dict(steps=30, seed=2, cfg=5.0, state_cfg=1.0, action_cfg=1.0, num_frames=101, fps=20, width=832, height=480, state_sampling='end', dtype='bfloat16')
EXPECTED_SCRIPTS = {'scripts/generate_proxy_benchmark.py':'f2d17445bca9609b20df6ef5a578e999c7789058cbbd7fbcdccd998c63eecc54', 'stateplay_eval.py':'690de8f55cf176cf365d76a144cff546113e4fb28e1c6ddaa18e293a54f0b552'}


def now(): return datetime.datetime.now(datetime.timezone.utc).isoformat()
def write_json(p, value):
 p.parent.mkdir(parents=True, exist_ok=True); temp=p.with_suffix(p.suffix+'.tmp');temp.write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n');temp.replace(p)
def sha(p):
 h=hashlib.sha256()
 with Path(p).open('rb') as f:
  for b in iter(lambda:f.read(16*1024*1024),b''):h.update(b)
 return h.hexdigest()
def check(condition, message):
 if not condition: raise RuntimeError(message)
def csv_rows(p):
 with Path(p).open(encoding='utf-8-sig',newline='') as f:return list(csv.DictReader(f))
def zip_rows(z,p):return list(csv.DictReader(io.StringIO(z.read(p).decode('utf-8-sig'))))
def write_csv(p,rows):
 p.parent.mkdir(parents=True,exist_ok=True)
 with p.open('w',encoding='utf-8-sig',newline='') as f:
  w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
def status(stage, **details):
 value=dict(time=now(),stage=stage,checkpoint=str(CHECKPOINT),checkpoint_sha256=MODEL_SHA,run_name=RUN_NAME,**details)
 write_json(BENCH/'status.json',value);print(now(),stage,json.dumps(details,ensure_ascii=False),flush=True)
def header(p):
 with Path(p).open('rb') as f:return json.loads(f.read(struct.unpack('<Q',f.read(8))[0]))


def preflight():
 status('preflight')
 check(CHECKPOINT.is_file(),f'Missing exact checkpoint: {CHECKPOINT}')
 check(sha(CHECKPOINT)==MODEL_SHA,'New checkpoint SHA256 differs; refusing inference')
 h=header(CHECKPOINT);old=header(ROOT/'outputs/latent_world/step-4572.safetensors')
 check(set(h)==set(old) and all((h[k]['shape'],h[k]['dtype'])==(old[k]['shape'],old[k]['dtype']) for k in h),'New checkpoint schema differs from the previously supported latent architecture')
 check(any(k.startswith('latent_state_rollout.') for k in h) and not any(k.startswith(('state_encoder.','state_decoder.')) for k in h),'Expected latent-state checkpoint, not explicit/official architecture')
 for rel,digest in EXPECTED_SCRIPTS.items():check(sha(ROOT/rel)==digest,f'Existing inference/evaluation script has changed: {rel}')
 for rel in ['Wan-AI/Wan2.2-TI2V-5B/Wan2.2_VAE.pth','Wan-AI/Wan2.2-TI2V-5B/models_t5_umt5-xxl-enc-bf16.pth','Wan-AI/Wan2.1-T2V-1.3B/google/umt5-xxl/spiece.model']:
  check((ROOT/'base_model'/rel).is_file(),f'Missing base asset: {rel}')
 check(len(list((ROOT/'base_model/Wan-AI/Wan2.2-TI2V-5B').glob('diffusion_pytorch_model-*.safetensors')))==3,'Expected three Wan base DiT shards')
 # Freeze this run's code; future edits in the main tree must not alter in-flight jobs.
 if not SOURCE.exists():
  SOURCE.mkdir(parents=True)
  ignore=shutil.ignore_patterns('__pycache__','*.pyc','.ipynb_checkpoints')
  for rel in ['stateplay','diffsynth','training']:shutil.copytree(ROOT/rel,SOURCE/rel,ignore=ignore)
  (SOURCE/'scripts').mkdir()
  for rel in ['scripts/generate_proxy_benchmark.py','scripts/verify_new_generation_outputs.py','stateplay_eval.py']:
   shutil.copyfile(ROOT/rel,SOURCE/rel)
  (SOURCE/'assets').mkdir()
  for name in ['macro_success.png','result_win.png','result_lose.png']:shutil.copyfile(ROOT/'assets'/name,SOURCE/'assets'/name)
  write_json(BENCH/'source_snapshot_identity.json',{str(p.relative_to(SOURCE)):sha(p) for p in SOURCE.rglob('*') if p.is_file()})
 else:
  for rel,digest in json.loads((BENCH/'source_snapshot_identity.json').read_text()).items():check(sha(SOURCE/rel)==digest,f'Frozen source changed: {rel}')
 for rel,digest in EXPECTED_SCRIPTS.items():check(sha(SOURCE/rel)==digest,f'Wrong frozen source: {rel}')
 bundle_manifest=json.loads((BUNDLE/'FILE_MANIFEST.json').read_text())
 for rel,info in bundle_manifest['files'].items():check(sha(BUNDLE/rel)==info['sha256'],f'HUD bundle changed: {rel}')
 sys.path.insert(0,str(BUNDLE))
 from evaluation.hud.common import load_states
 selections={};metas={};groups={};identities={};source100={}
 historical=json.loads((ROOT/'evaluation/test_200_train_ratio/selection.json').read_text());past={s['source_id']:s for s in historical['samples']}
 for ds,(archive,digest,prefix,data) in ARCHIVES.items():
  check(sha(archive)==digest,f'Wrong test ZIP: {archive}')
  with zipfile.ZipFile(archive) as z:
   rows=zip_rows(z,prefix+'metadata_state_polish.csv');metas[ds]=rows
   count=200 if ds=='test200' else 100;check(len(rows)==count,f'Wrong metadata count: {ds}')
   check(rows==csv_rows(data/'metadata_state_polish.csv'),f'Extracted metadata differs: {ds}')
   groups[ds]={r['clip_id']:r for r in zip_rows(z,prefix+'selection_manifest.csv')}
   if ds=='test100':source100={r['clip_id']:r for r in zip_rows(z,prefix+'qa/source_provenance.csv')}
   samples=[]
   for index,row in enumerate(rows,1):
    clip=Path(row['video']).parent.name;hashes={}
    for name,rel in [('video',row['video']),('actions',row['action']),('first_frame',str(Path(row['video']).parent/'first_frame.png'))]:
     digest_asset=hashlib.sha256(z.read(prefix+rel)).hexdigest();check(sha(data/rel)==digest_asset,f'Asset differs from ZIP: {ds}/{clip}/{name}');hashes[name]=digest_asset
    check(load_states(data/row['action']).shape==(100,5),f'Invalid actual state timeline: {ds}/{clip}')
    label=row['distribution'].lower();sid=f"{'tr200' if ds=='test200' else 'tr100'}_{index:04d}"
    sample=dict(id=sid,source_kind=RUN_NAME+'_'+ds,source_id=clip,label=label,input_image=str(data/Path(row['video']).parent/'first_frame.png'),source_video=str(data/row['video']),reference_video=str(data/row['video']),actions=str(data/row['action']),prompt=row['prompt'],output_name=f'{sid}_{label}_{clip}.mp4',identity=hashes)
    if ds=='test200':
     s=past[clip];check(s['prompt']==sample['prompt'] and s['label']==label,'Historical generation inputs differ')
     check(hashes['video']==s['identity']['video_sha256'] and hashes['actions']==s['identity']['actions_file_sha256'] and hashes['first_frame']==s['identity']['first_frame_sha256'],'Historical asset hashes differ')
    identities[(ds,clip)]=hashes;samples.append(sample)
   check(len({s['source_id'] for s in samples})==count,'Duplicate clip IDs')
   from collections import Counter
   check(Counter(s['label'] for s in samples)==dict(normal=count*6//10,macro_success=count//10,macro_fail=count//10,result_win=count//10,result_lose=count//10),'Unexpected class distribution')
   selections[ds]=dict(benchmark_name=RUN_NAME+'_'+ds,checkpoint=str(CHECKPOINT),checkpoint_sha256=MODEL_SHA,source_archive=str(archive),source_archive_sha256=digest,dataset_root=str(data),samples=samples)
   print('Verified original archive, all recorded assets and labels:',ds,count,flush=True)
 by200={s['source_id']:s for s in selections['test200']['samples']};mapping=[]
 for s in selections['test100']['samples']:
  source=source100[s['source_id']];mapped=source['verified_200_clip_id'];t=by200[mapped]
  check(s['identity']==t['identity'] and (s['prompt'],s['label'])==(t['prompt'],t['label']),'100 -> 200 inputs do not match exactly')
  mapping.append(dict(clip_id_100=s['source_id'],clip_id_200=mapped,id_100=s['id'],id_200=t['id'],output_100=s['output_name'],output_200=t['output_name']))
 check(len({m['clip_id_200'] for m in mapping})==100,'100 subset duplicates')
 write_csv(BENCH/'test100_to_test200_mapping.csv',mapping)
 for ds,selection in selections.items():
  p=BENCH/ds;p.mkdir(exist_ok=True);write_json(p/'selection.json',selection)
  visual=[];mechanics=[];hud=[]
  for s in selection['samples']:
   pred=str(p/'generated'/RUN_NAME/s['output_name']);g=groups[ds][s['source_id']]
   group=g.get('recording_root','')+'|'+g['episode_id'] if g.get('episode_id') else s['source_id']
   visual.append(dict(id=s['id'],prediction=pred,reference=s['source_video'],label=s['label']))
   mechanics.append(dict(id=s['id'],prediction=pred,label=s['label']))
   hud.append(dict(id=s['source_id'],prediction=pred,recorded=s['actions'],distribution=s['label'],source_group=group))
  write_csv(p/'manifest_visual.csv',visual);write_csv(p/'manifest_mechanics.csv',mechanics);write_csv(p/'manifest_hud.csv',hud)
 identity=dict(checkpoint=str(CHECKPOINT),checkpoint_sha256=MODEL_SHA,bytes=CHECKPOINT.stat().st_size,mtime_ns=CHECKPOINT.stat().st_mtime_ns,architecture='latent-state',parameters=PARAMETERS,exact_100_subset_verified=True,distinct_inference_inputs=200,test100_samples=100,test200_samples=200,inference_script_sha256=EXPECTED_SCRIPTS['scripts/generate_proxy_benchmark.py'],original_evaluator_sha256=EXPECTED_SCRIPTS['stateplay_eval.py'],hud_checkpoint_sha256=sha(BUNDLE/'evaluation/hud_runs/reader_full/reader_final.pt'),model_role='user newly trained checkpoint; not official and not outputs/latent_world/step-3000',source_snapshot=str(SOURCE))
 existing=BENCH/'model_identity.json'
 if existing.exists():
  prev=json.loads(existing.read_text());check(prev==identity,'Existing run identity differs; refusing reuse')
 write_json(existing,identity)
 versions={n:importlib.metadata.version(n) for n in ['torch','torchvision','numpy','Pillow','imageio','pyarrow','lpips','scikit-image']}
 write_json(BENCH/'environment.json',dict(python=sys.version,executable=sys.executable,packages=versions))
 status('preflight_passed',datasets=['test200','test100'],parameters=PARAMETERS)
 return selections,mapping


def valid_video(p):
 import cv2
 if not p.is_file() or p.stat().st_size<1024:return False
 c=cv2.VideoCapture(str(p))
 try:
  n=int(c.get(cv2.CAP_PROP_FRAME_COUNT)); fps=c.get(cv2.CAP_PROP_FPS);w=int(c.get(cv2.CAP_PROP_FRAME_WIDTH));h=int(c.get(cv2.CAP_PROP_FRAME_HEIGHT))
  first=c.read()[0];c.set(cv2.CAP_PROP_POS_FRAMES,100);last=c.read()[0]
  return n==101 and abs(fps-20)<.01 and (w,h)==(832,480) and first and last
 finally:c.release()


def command(stage,cmd,cwd=ROOT,env=None,attempts=3):
 marker=BENCH/'stages'/f'{stage}.json';log=BENCH/'logs'/f'{stage}.log';log.parent.mkdir(parents=True,exist_ok=True)
 if marker.exists():
  record=json.loads(marker.read_text());check(record['command']==list(map(str,cmd)),'Completed stage command mismatch');print('Resume completed stage:',stage,flush=True);return
 for attempt in range(1,attempts+1):
  status(stage,attempt=attempt,log=str(log))
  with log.open('ab') as f:
   p=subprocess.Popen(list(map(str,cmd)),cwd=cwd,env=env,stdin=subprocess.DEVNULL,stdout=f,stderr=subprocess.STDOUT)
   write_json(BENCH/'active_stage.json',dict(stage=stage,pid=p.pid,log=str(log),command=list(map(str,cmd))))
   code=p.wait()
  if code==0:write_json(marker,dict(time=now(),command=list(map(str,cmd)),exit_code=0));return
  print('Stage failed:',stage,'attempt',attempt,'exit',code,'see',log,flush=True)
  if attempt<attempts:time.sleep(min(attempt*30,60))
 raise RuntimeError(f'{stage} failed after {attempts} attempts; see {log}')


def infer(selections,gpus,stagger):
 selection=selections['test200'];directory=BENCH/'test200/generated'/RUN_NAME;directory.mkdir(parents=True,exist_ok=True)
 # A controller restart must leave already-running GPU workers alone and wait for them.
 process_record=BENCH/'inference_processes.json'
 if process_record.exists():
  previous=json.loads(process_record.read_text()).get('processes',[])
  adopted=[]
  for job in previous:
   process=Path('/proc')/str(job['pid'])
   if not process.exists():continue
   try:
    argv=(process/'cmdline').read_bytes().split(b'\0')
    state=next(line for line in (process/'status').read_text().splitlines() if line.startswith('State:'))
   except FileNotFoundError:continue
   if '(zombie)' in state:continue
   check(str(CHECKPOINT).encode() in argv and str(SOURCE/'scripts/generate_proxy_benchmark.py').encode() in argv,'Refusing to adopt an unrelated worker')
   adopted.append(job)
  if adopted:
   write_json(BENCH/'adopted_inference_workers.json',dict(time=now(),workers=adopted,checkpoint_sha256=MODEL_SHA))
   while adopted:
    live=[]
    for job in adopted:
     process=Path('/proc')/str(job['pid'])
     try:
      state=next(line for line in (process/'status').read_text().splitlines() if line.startswith('State:'))
      if '(zombie)' not in state:live.append(job)
     except FileNotFoundError:pass
    adopted=live
    if adopted:
     status('inference_test200',adopted_workers=len(adopted),note='existing GPU inference continues without restart')
     time.sleep(30)
 def quarantine_invalid():
  for p in list(directory.glob('*.mp4')):
   if p.name.endswith('.tmp.mp4') or not valid_video(p):
    q=BENCH/'quarantine';q.mkdir(exist_ok=True);p.replace(q/(str(time.time_ns())+'_'+p.name))
 quarantine_invalid()
 attempts=3
 for attempt in range(1,attempts+1):
  pending=[i for i in range(len(gpus)) if any(not (directory/s['output_name']).is_file() for j,s in enumerate(selection['samples']) if j%len(gpus)==i)]
  if not pending:break
  status('inference_test200',attempt=attempt,gpus=gpus,shards=pending)
  processes=[]
  for index,shard in enumerate(pending):
   ident=json.loads((BENCH/'model_identity.json').read_text());check(CHECKPOINT.stat().st_size==ident['bytes'] and CHECKPOINT.stat().st_mtime_ns==ident['mtime_ns'],'Checkpoint changed after preflight')
   env=os.environ.copy();env.update(CUDA_VISIBLE_DEVICES=str(gpus[shard]),TOKENIZERS_PARALLELISM='false',PYTHONUNBUFFERED='1')
   log=BENCH/'logs'/f'inference_shard_{shard}_attempt_{attempt}.log';handle=log.open('wb')
   cmd=[sys.executable,'-u',str(SOURCE/'scripts/generate_proxy_benchmark.py'),'--manifest',str(BENCH/'test200/selection.json'),'--checkpoint',str(CHECKPOINT),'--run-name',RUN_NAME,'--base-model',str(ROOT/'base_model'),'--output-root',str(BENCH/'test200/generated'),'--shard-index',str(shard),'--num-shards',str(len(gpus)),'--steps','30','--cfg','5.0','--action-cfg','1.0','--seed','2','--skip-existing']
   p=subprocess.Popen(cmd,cwd=SOURCE,env=env,stdin=subprocess.DEVNULL,stdout=handle,stderr=subprocess.STDOUT);processes.append((p,handle,log))
   write_json(BENCH/'inference_processes.json',dict(attempt=attempt,processes=[dict(pid=p.pid,log=str(l)) for p,_,l in processes]))
   print('Started inference shard',shard,'GPU',gpus[shard],'PID',p.pid,flush=True)
   if index<len(pending)-1 and stagger:time.sleep(stagger)
  for p,handle,log in processes:
   code=p.wait();handle.close()
   text=log.read_text(errors='replace')
   check(code!=0 or 'architecture=latent-state loaded: 1319 keys (30 action_embedders, 0 state keys), missing=0, unexpected=0' in text,'Inference loaded an unexpected architecture')
   if code:print('Inference worker failed',p.pid,code,'see',log,flush=True)
  quarantine_invalid()
  if all((directory/s['output_name']).is_file() for s in selection['samples']):break
 check(all((directory/s['output_name']).is_file() for s in selection['samples']),'Some new-model videos are missing after retries')
 command('verify_test200',[sys.executable,str(SOURCE/'scripts/verify_new_generation_outputs.py'),'--selection',str(BENCH/'test200/selection.json'),'--generated-root',str(BENCH/'test200/generated'),'--run-name',RUN_NAME,'--expected-count','200'])
 return directory


def subset(mapping,directory):
 target=BENCH/'test100/generated'/RUN_NAME;target.mkdir(parents=True,exist_ok=True)
 for m in mapping:
  p=target/m['output_100'];source=directory/m['output_200']
  if p.is_symlink():check(p.resolve()==source.resolve(),'Existing subset link differs')
  elif p.exists():check(sha(p)==sha(source),'Existing subset video differs')
  else:p.symlink_to(os.path.relpath(source,target))
 command('verify_test100',[sys.executable,str(SOURCE/'scripts/verify_new_generation_outputs.py'),'--selection',str(BENCH/'test100/selection.json'),'--generated-root',str(BENCH/'test100/generated'),'--run-name',RUN_NAME,'--expected-count','100'])
 evidence=[]
 for ds in ['test200','test100']:
  selection=json.loads((BENCH/ds/'selection.json').read_text())
  for s in selection['samples']:
   p=BENCH/ds/'generated'/RUN_NAME/s['output_name'];evidence.append(dict(dataset=ds,id=s['id'],source_id=s['source_id'],prediction=str(p),resolved_prediction=str(p.resolve()),bytes=p.stat().st_size,prediction_sha256=sha(p),checkpoint_sha256=MODEL_SHA))
 write_csv(BENCH/'generated_video_identity.csv',evidence)


def load_credentials(path=None):
 values={n:os.environ.get(n,'').strip() for n in KEY_NAMES}
 if path:
  text=Path(path).read_text()
  try:data=json.loads(text)
  except json.JSONDecodeError:
   data={}
   for line in text.splitlines():
    line=line.strip()
    if line.startswith('export '):line=line[7:]
    if not line or line.startswith('#') or '=' not in line:continue
    k,v=line.split('=',1);data[k.strip()]=v.strip().strip('"\'')
  for n in KEY_NAMES:
   if data.get(n):values[n]=str(data[n]).strip()
 return values


def credential_channel(initial):
 values=initial.copy();ready=threading.Event();fifo=BENCH/'credentials_fifo_path.txt'
 tempdir=Path('/tmp')/RUN_NAME;tempdir.mkdir(mode=0o700,exist_ok=True);pipe=tempdir/'judge_credentials.fifo'
 if pipe.exists():pipe.unlink()
 os.mkfifo(pipe,0o600);fifo.write_text(str(pipe)+'\n')
 def receive():
  fd=os.open(pipe,os.O_RDONLY|os.O_NONBLOCK);buffer=b''
  try:
   while not ready.is_set():
    try:chunk=os.read(fd,65536)
    except BlockingIOError:
     time.sleep(.5);continue
    if chunk:
     buffer+=chunk
     if b'\n' in buffer:
      try:
       data=json.loads(buffer.split(b'\n',1)[0]);incoming={n:str(data.get(n,'')).strip() for n in KEY_NAMES}
       if all(incoming.values()):values.update(incoming);ready.set();print('Judge credentials received in memory.',flush=True)
       else:print('Incomplete credential submission; waiting for both required keys.',flush=True)
      except (ValueError,TypeError):print('Invalid credential submission; no secret values logged.',flush=True)
      buffer=b''
    time.sleep(.5)
  finally:os.close(fd)
 if all(values.values()):ready.set()
 else:threading.Thread(target=receive,daemon=True).start()
 return values,ready,pipe


def run(args):
 BENCH.mkdir(parents=True,exist_ok=True);(BENCH/'logs').mkdir(exist_ok=True)
 lock=(BENCH/'.run.lock').open('a')
 try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
 except BlockingIOError:raise RuntimeError('This exact model/test run is already active')
 values,ready,pipe=credential_channel(load_credentials(args.credential_file))
 try:
  selections,mapping=preflight();directory=infer(selections,args.gpus.split(','),args.stagger);subset(mapping,directory)
  # Both fully local evaluations finish before waiting for remote judge credentials.
  for ds in ['test200','test100']:
   p=BENCH/ds
   command('visual_'+ds,[sys.executable,str(SOURCE/'stateplay_eval.py'),'--manifest',str(p/'manifest_visual.csv'),'--output',str(p/'results_visual.json'),'--visual-metrics','ssim','lpips','--mechanics','none','--device','cuda:0','--lpips-batch-size','8'])
   command('hud_'+ds,[sys.executable,'-u','-m','evaluation.hud.evaluate','--manifest',str(p/'manifest_hud.csv'),'--geometry','cover','--exclude-first','--device','cuda','--output',str(p/'hud_results')],cwd=BUNDLE)
  if not ready.is_set():
   status('waiting_for_judge_credentials',local_evaluations='complete',supply_command='bash scripts/run_new_step3000_two_tests.sh --supply-credentials',credentials_never_saved_to_disk=True)
   ready.wait()
  import importlib.util
  api_spec=importlib.util.spec_from_file_location('step3000_api_resume',ROOT/'scripts/resume_step3000_api_eval.py')
  api_runner=importlib.util.module_from_spec(api_spec);api_spec.loader.exec_module(api_runner)
  api_runner.run(argparse.Namespace(credential_file=None),lock_already_held=True,credentials=values)
 except BaseException as exc:
  # Exception messages here only describe stages/files; credential contents never enter them.
  status('failed',error=str(exc));raise
 finally:
  if pipe.exists():pipe.unlink()
  lock.close()


def main():
 parser=argparse.ArgumentParser(description=__doc__)
 parser.add_argument('--detach',action='store_true');parser.add_argument('--preflight-only',action='store_true');parser.add_argument('--supply-credentials',action='store_true');parser.add_argument('--credential-file',type=Path)
 parser.add_argument('--gpus',default='0,1,2,3,4,5,6');parser.add_argument('--stagger',type=int,default=60)
 args=parser.parse_args();os.umask(0o077)
 if args.supply_credentials:
  values=load_credentials(args.credential_file)
  if not all(values.values()):
   if not sys.stdin.isatty():raise SystemExit('Set both STATEPLAY_GPT_API_KEY and STATEPLAY_GEMINI_API_KEY in the environment, or provide --credential-file; do not put keys in command arguments.')
   import getpass
   for n in KEY_NAMES:
    if not values[n]:values[n]=getpass.getpass(n+': ').strip()
  check(all(values.values()),'Both judge credentials are required')
  pipe=Path((BENCH/'credentials_fifo_path.txt').read_text().strip());fd=os.open(pipe,os.O_WRONLY|os.O_NONBLOCK)
  try:os.write(fd,(json.dumps(values)+'\n').encode())
  finally:os.close(fd)
  print('Credentials delivered to the running batch in memory; no secret file written.');return
 if args.preflight_only:
  BENCH.mkdir(parents=True,exist_ok=True);preflight();return
 if args.detach:
  BENCH.mkdir(parents=True,exist_ok=True);log=BENCH/'logs/launcher.log';log.parent.mkdir(exist_ok=True)
  cmd=[sys.executable,'-u',str(Path(__file__).resolve()),'--gpus',args.gpus,'--stagger',str(args.stagger)]
  if args.credential_file:cmd+=['--credential-file',str(args.credential_file.resolve())]
  with log.open('ab') as f:p=subprocess.Popen(cmd,cwd=ROOT,stdin=subprocess.DEVNULL,stdout=f,stderr=subprocess.STDOUT,start_new_session=True)
  (BENCH/'launcher.pid').write_text(str(p.pid)+'\n');time.sleep(2)
  check(p.poll() is None,f'Batch exited during startup; see {log}')
  print(json.dumps(dict(pid=p.pid,model=str(CHECKPOINT),checkpoint_sha256=MODEL_SHA,benchmark=str(BENCH),log=str(log)),indent=2));return
 run(args)

if __name__=='__main__':main()