#!/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(' 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