#!/usr/bin/env python """Edit-eval for the orbit-alpha project, run on GPU jobs. Modes: ab : first 10 train pairs through the base model with two caption variants (with / without the transparency sentence) -> pick caption. baseline : eval-pair list through the untouched base model, both grammars (plain + ), metrics per edit. lora : eval-pair list (or a subset) through a loaded LoRA, grammar. Metrics per edit (fixed seed): alpha IoU vs GT mask (alpha>0.5), LPIPS (alex) and PSNR on the mid-gray composite (128), DINOv2-base CLS cosine similarity on the mid-gray composite. Metric models run on CPU so the GPU stays with the pipeline. Per-pair generator seed is deterministic (crc32 of pair_id + SEED). Timing: seconds per edit measured per run. Usage: python eval_edit.py --mode baseline --pairs pairs_eval.jsonl --out /out/baseline python eval_edit.py --mode ab --pairs pairs_train.jsonl --out /out/ab python eval_edit.py --mode lora --pairs pairs_eval.jsonl --out /out/lora \ --lora /ckpts/orbit_lora_000002000.safetensors [--limit 48] """ import argparse, json, os, time, zlib import numpy as np import torch from PIL import Image from huggingface_hub import hf_hub_download from diffusers import QwenImage21Pipeline DS_REPO = 'ysharma/gso-orbit-rgba' GRAY = 128.0 SEED = 42 STEPS = 40 SIZE = 768 ALPHA_SUFFIX = "The image has alpha channel and the background is transparent." _file_cache = {} _pair_cache = {} def pair_seed(pid): return SEED + (zlib.crc32(pid.encode()) % 100000) def get_file(name): if name not in _file_cache: _file_cache[name] = hf_hub_download(repo_id=DS_REPO, repo_type='dataset', filename=name) return _file_cache[name] def composite(img_rgba): arr = np.asarray(img_rgba).astype(np.float32) a = arr[..., 3:4] / 255.0 rgb = arr[..., :3] return np.clip(rgb * a + GRAY * (1.0 - a), 0, 255).astype(np.uint8) def make_metrics(): import lpips from transformers import AutoImageProcessor, AutoModel lp = lpips.LPIPS(net='alex') dino_model = AutoModel.from_pretrained('facebook/dinov2-base') dino_proc = AutoImageProcessor.from_pretrained('facebook/dinov2-base') dino_model.eval() return lp, dino_model, dino_proc def metrics_v(pred_rgba, gt_rgba, m): lp, dino_model, dino_proc = m pm = np.asarray(pred_rgba)[..., 3] > 127 gm = np.asarray(gt_rgba)[..., 3] > 127 inter = np.logical_and(pm, gm).sum() union = np.logical_or(pm, gm).sum() a_iou = float(inter) / max(float(union), 1.0) pc = composite(pred_rgba) gc = composite(gt_rgba) mse = float(np.mean((pc.astype(np.float64) - gc.astype(np.float64)) ** 2)) psnr = 99.0 if mse < 1e-10 else 10.0 * np.log10(255.0 ** 2 / mse) pc_t = torch.from_numpy(pc).permute(2, 0, 1)[None].float() * 2 - 1 gc_t = torch.from_numpy(gc).permute(2, 0, 1)[None].float() * 2 - 1 with torch.no_grad(): lp_v = float(lp(pc_t, gc_t).item()) pg = dino_model(**dino_proc(images=Image.fromarray(pc), return_tensors='pt')).last_hidden_state[:, 0] gg = dino_model(**dino_proc(images=Image.fromarray(gc), return_tensors='pt')).last_hidden_state[:, 0] dino_sim = float(torch.cosine_similarity(pg, gg, dim=-1).item()) return {'alpha_iou': round(a_iou, 4), 'lpips': round(lp_v, 4), 'psnr': round(float(psnr), 2), 'dino_sim': round(dino_sim, 4)} def load_pipe(): pipe = QwenImage21Pipeline.from_pretrained('Qwen/Qwen-Image-2.1', dtype=torch.bfloat16) pipe.to('cuda') return pipe def run_pairs(pipe, m, pairs, prompts_key, out_dir): os.makedirs(out_dir, exist_ok=True) rows = [] for i, p in enumerate(pairs): pid = p['pair_id'] if pid not in _pair_cache: src = Image.open(get_file(p['source_file'])).convert('RGBA') gt = Image.open(get_file(p['target_file'])).convert('RGBA') _pair_cache[pid] = (src, gt) src, gt = _pair_cache[pid] prompt = p[prompts_key] gen = torch.Generator('cuda').manual_seed(pair_seed(pid)) t0 = time.time() out = pipe(prompt=prompt, image=src, width=SIZE, height=SIZE, num_inference_steps=STEPS, generator=gen, use_kv_cache=True).images[0] dt = time.time() - t0 mv = metrics_v(out, gt, m) out.convert('RGBA').save(os.path.join(out_dir, f'{pid}.png')) rec = {'pair_id': pid, 'object_id': p['object_id'], 'move_deg': p['move_deg'], 'elevation': p['elevation'], 's_edit': round(dt, 2), **mv} rows.append(rec) if (i + 1) % 10 == 0: print(f' {i+1}/{len(pairs)} edits done | last s/edit {dt:.1f}s', flush=True) print(json.dumps(rec), flush=True) with open(os.path.join(out_dir, 'results.jsonl'), 'w') as f: for r in rows: f.write(json.dumps(r) + '\n') return rows def agg(rows, label): def block(sel, name): sel = [r for r in rows if sel(r)] if not sel: return print(f'{label} | {name}: n={len(sel)} ' f"aIoU={np.mean([r['alpha_iou'] for r in sel]):.3f} " f"LPIPS={np.mean([r['lpips'] for r in sel]):.3f} " f"PSNR={np.mean([r['psnr'] for r in sel]):.2f} " f"DINO={np.mean([r['dino_sim'] for r in sel]):.3f} " f"s/edit={np.mean([r['s_edit'] for r in sel]):.1f}", flush=True) block(lambda r: True, 'ALL') for d in (45, 90, 135, 180, 0): block(lambda r, d=d: r['move_deg'] == d, f'move{d}') block(lambda r: r['elevation'] != 'eye', 'elev-change') block(lambda r: r['elevation'] == 'eye', 'elev-none') def main(): ap = argparse.ArgumentParser() ap.add_argument('--mode', required=True, choices=['ab', 'baseline', 'lora']) ap.add_argument('--pairs', required=True) ap.add_argument('--out', required=True) ap.add_argument('--lora', default=None) ap.add_argument('--limit', type=int, default=0) args = ap.parse_args() pairs = [json.loads(l) for l in open(get_file(args.pairs))] if args.limit: pairs = pairs[:args.limit] pipe = load_pipe() m = make_metrics() if args.mode == 'ab': pairs = pairs[:10] rows = [] for variant, suffix in (('no_suffix', ''), ('suffix', ' ' + ALPHA_SUFFIX)): pv = [dict(p, instruction=p['instruction'] + suffix) for p in pairs] r = run_pairs(pipe, m, pv, 'instruction', os.path.join(args.out, variant)) agg(r, f'AB/{variant}') rows.extend([dict(x, variant=variant) for x in r]) with open(os.path.join(args.out, 'ab_results.jsonl'), 'w') as f: for r in rows: f.write(json.dumps(r) + '\n') elif args.mode == 'baseline': for key, name in (('instruction_plain', 'plain'), ('instruction', 'orbit')): r = run_pairs(pipe, m, pairs, key, os.path.join(args.out, name)) agg(r, f'BASE/{name}') else: assert args.lora, '--lora required' pipe.load_lora_weights(args.lora) r = run_pairs(pipe, m, pairs, 'instruction', args.out) agg(r, 'LORA') if __name__ == '__main__': main()