#!/usr/bin/env python """Checkpoint selection for the orbit-alpha LoRA. Fixed 48-edit subset (first 12 eval objects x 4 pairs) at 20 steps, for the untouched base model AND every saved checkpoint, all through ONE pipeline load (adapter unload/load between checkpoints). Choice rule per spec: best LPIPS that does not lose alpha IoU vs the base model. Usage: python select_ckpt.py --out /out/ckpt_select Uploads summary + per-edit results to ysharma/gso-orbit-rgba/eval/ckpt_select/. """ import argparse, json, os, collections import numpy as np import eval_edit as ee # 20-step selection pass, per spec (ee.run_pairs reads module-level STEPS) ee.STEPS = 20 MODEL_REPO = 'ysharma/orbit-alpha-lora' CKPT_DIR = 'checkpoints/steps2000res768/orbit_alpha_lora' CKPTS = [ ('ckpt500', f'{CKPT_DIR}/orbit_alpha_lora_000000500.safetensors'), ('ckpt1000', f'{CKPT_DIR}/orbit_alpha_lora_000001000.safetensors'), ('ckpt1500', f'{CKPT_DIR}/orbit_alpha_lora_000001500.safetensors'), ('ckpt2000', f'{CKPT_DIR}/orbit_alpha_lora.safetensors'), ] DS_REPO = ee.DS_REPO OUT_REPO_PATH = 'eval/ckpt_select' def pick_subset(pairs, n_obj=12): by_obj = collections.OrderedDict() for p in pairs: by_obj.setdefault(p['object_id'], []).append(p) objs = list(by_obj)[:n_obj] sel = [p for o in objs for p in by_obj[o]] assert len(objs) == n_obj and all(len(by_obj[o]) == 4 for o in objs), \ f'expected {n_obj} objects x 4 pairs, got {len(objs)} objs' return sel def swap_adapter(pipe, path): try: pipe.unload_lora_weights() except Exception as e: print(f'[swap] unload_lora_weights failed ({e!r}); continuing with load', flush=True) pipe.load_lora_weights(path) print(f'[swap] loaded {path}', flush=True) def agg_rows(rows, label): a = float(np.mean([r['alpha_iou'] for r in rows])) l = float(np.mean([r['lpips'] for r in rows])) p = float(np.mean([r['psnr'] for r in rows])) d = float(np.mean([r['dino_sim'] for r in rows])) s = float(np.mean([r['s_edit'] for r in rows])) print(f'{label}: n={len(rows)} aIoU={a:.3f} LPIPS={l:.4f} PSNR={p:.2f} DINO={d:.3f} s/edit={s:.1f}', flush=True) return {'name': label, 'n': len(rows), 'alpha_iou': round(a, 4), 'lpips': round(l, 4), 'psnr': round(p, 2), 'dino_sim': round(d, 4), 's_edit': round(s, 2)} def upload(local, remote): from huggingface_hub import HfApi HfApi().upload_file(path_or_fileobj=local, path_in_repo=remote, repo_id=DS_REPO, repo_type='dataset', commit_message=f'ckpt-select: {remote}') def main(): ap = argparse.ArgumentParser() ap.add_argument('--out', required=True) args = ap.parse_args() os.makedirs(args.out, exist_ok=True) pairs = pick_subset([json.loads(l) for l in open(ee.get_file('pairs_eval.jsonl'))]) print(f'subset: {len(pairs)} edits, objects={sorted({p["object_id"] for p in pairs})[:3]}...', flush=True) pipe = ee.load_pipe() m = ee.make_metrics() summary = [] # base model at 20 steps first (reference point) rows = ee.run_pairs(pipe, m, pairs, 'instruction', os.path.join(args.out, 'base20')) summary.append(agg_rows(rows, 'base20')) base_aiou = summary[0]['alpha_iou'] for name, path in CKPTS: local = ee.hf_hub_download(repo_id=MODEL_REPO, repo_type='model', filename=path) swap_adapter(pipe, local) rows = ee.run_pairs(pipe, m, pairs, 'instruction', os.path.join(args.out, name)) r = agg_rows(rows, name) r['kept_aiou'] = bool(r['alpha_iou'] >= base_aiou) summary.append(r) # choice rule: best LPIPS among checkpoints that do not lose alpha IoU ok = [s for s in summary[1:] if s['kept_aiou']] chosen = min(ok, key=lambda s: s['lpips']) if ok else None if chosen is None: chosen = min(summary[1:], key=lambda s: s['lpips']) print('WARNING: no checkpoint kept base alpha IoU; fell back to best LPIPS overall', flush=True) summary.append({'chosen': chosen['name']}) with open(os.path.join(args.out, 'summary.json'), 'w') as f: json.dump(summary, f, indent=2) print('SUMMARY ' + json.dumps(summary), flush=True) upload(os.path.join(args.out, 'summary.json'), f'{OUT_REPO_PATH}/summary.json') for name, _ in [('base20', None)] + CKPTS: upload(os.path.join(args.out, name, 'results.jsonl'), f'{OUT_REPO_PATH}/{name}_results.jsonl') print('DONE', flush=True) if __name__ == '__main__': main()