gso-orbit-rgba / gate_lora.py
ysharma's picture
ysharma HF Staff
Fix metrics plumbing: metrics_v expects the (lp, dino_model, dino_proc) tuple, not a dict — dict unpacking bound lp to the string 'lp'
05cfd23 verified
Raw History Blame
7.04 kB
#!/usr/bin/env python
"""50-step gate for the orbit-alpha LoRA (run on a GPU job).
Checks, in order:
1. lora_B audit : every lora_B tensor in the saved adapter must be non-zero
(min |mean| > 1e-8). Guards against the all-zero-lora_B bug.
2. diffusers load : QwenImage21Pipeline.load_lora_weights must accept the
ai-toolkit (ComfyUI-keyed) file without conversion.
3. visible change : the adapter must change the output on TRAINING pairs
(LPIPS between base and adapter output > 0.02) and must
not break the eval pairs (alpha IoU stays sane).
Outputs contact sheet + gate_results.json to the dataset repo eval/gate/<ckpt>/.
Prints a final 'GATE PASS' or 'GATE FAIL: <reason>' line.
Fix note: metrics_v() unpacks its third argument as a tuple
(lp, dino_model, dino_proc); pass METRICS (the tuple from make_metrics())
directly — building a dict here made lp bind to the string 'lp'.
"""
import argparse, json, os, sys
import numpy as np
import torch
from PIL import Image
from huggingface_hub import hf_hub_download, HfApi
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from eval_edit import (load_pipe, make_metrics, metrics_v, composite,
get_file, pair_seed, SIZE, STEPS)
CKPT_REPO = 'ysharma/orbit-alpha-lora'
DS_REPO = 'ysharma/gso-orbit-rgba'
def changed_lpips(lpf, img_a, img_b):
ca, cb = composite(img_a), composite(img_b)
ta = torch.from_numpy(ca).permute(2, 0, 1)[None].float() * 2 - 1
tb = torch.from_numpy(cb).permute(2, 0, 1)[None].float() * 2 - 1
with torch.no_grad():
return float(lpf(ta, tb).item())
def gen_rows(pipe, METRICS, pairs, out_dir, tag):
rows, imgs = [], {}
for p in pairs:
pid = p['pair_id']
src = Image.open(get_file(p['source_file'])).convert('RGBA')
gt = Image.open(get_file(p['target_file'])).convert('RGBA')
gen = torch.Generator('cuda').manual_seed(pair_seed(pid))
t0 = __import__('time').time()
out = pipe(prompt=p['instruction'], image=src, width=SIZE, height=SIZE,
num_inference_steps=STEPS, generator=gen,
use_kv_cache=True).images[0]
dt = __import__('time').time() - t0
mv = metrics_v(out, gt, METRICS)
imgs[pid] = out
rows.append({'pair_id': pid, 'tag': tag, 's_edit': round(dt, 2), **mv})
print(json.dumps(rows[-1]), flush=True)
out.convert('RGBA').save(os.path.join(out_dir, f'{tag}_{pid}.png'))
return rows, imgs
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--ckpt', default='steps50')
ap.add_argument('--out', default='/out/gate')
args = ap.parse_args()
os.makedirs(args.out, exist_ok=True)
# ---- 1. lora_B audit ------------------------------------------------
fname = f'checkpoints/{args.ckpt}/orbit_alpha_lora/orbit_alpha_lora.safetensors'
ckpt = hf_hub_download(CKPT_REPO, fname, repo_type='model')
print(f'ckpt: {fname} ({os.path.getsize(ckpt)/1e6:.1f} MB)', flush=True)
from safetensors.torch import load_file
sd = load_file(ckpt)
b_keys = [k for k in sd if 'lora_B' in k]
a_keys = [k for k in sd if 'lora_A' in k]
norms = [float(sd[k].abs().float().mean()) for k in b_keys]
zero_b = sum(1 for n in norms if n < 1e-8)
audit = {'n_lora_B': len(b_keys), 'n_lora_A': len(a_keys),
'n_all_zero_B': zero_b,
'min_mean_abs_B': min(norms) if norms else None,
'max_mean_abs_B': max(norms) if norms else None}
print('LORA_B AUDIT:', json.dumps(audit), flush=True)
# ---- 2. diffusers load (base rows first, THEN load adapter) ---------
pipe = load_pipe()
METRICS = make_metrics()
ev = [json.loads(l) for l in open(get_file('pairs_eval.jsonl'))][:4]
tr = [json.loads(l) for l in open(get_file('pairs_train.jsonl'))][:2]
base_rows, base_imgs = gen_rows(pipe, METRICS, tr + ev, args.out, 'base')
pipe.load_lora_weights(ckpt)
print('LOAD_LORA_WEIGHTS OK', flush=True)
lora_rows, lora_imgs = gen_rows(pipe, METRICS, tr + ev, args.out, 'lora')
# ---- 3. visible change ---------------------------------------------
ch = []
train_ids = {p['pair_id'] for p in tr}
for r_b, r_l in zip(base_rows, lora_rows):
c = changed_lpips(METRICS[0], base_imgs[r_b['pair_id']],
lora_imgs[r_b['pair_id']])
ch.append({'pair_id': r_b['pair_id'], 'is_train': r_b['pair_id'] in
train_ids, 'changed_lpips': round(c, 4)})
print(json.dumps(ch[-1]), flush=True)
tr_ch = [c['changed_lpips'] for c in ch if c['is_train']]
ev_ch = [c['changed_lpips'] for c in ch if not c['is_train']]
# ---- contact sheet ---------------------------------------------------
from PIL import ImageDraw
pairs_all = tr + ev
cell = 256
sheet = Image.new('RGB', (cell * 4, cell * len(pairs_all)), (30, 30, 30))
d = ImageDraw.Draw(sheet)
for i, p in enumerate(pairs_all):
pid = p['pair_id']
tiles = [composite(Image.open(get_file(p['source_file'])).convert('RGBA')),
composite(Image.open(get_file(p['target_file'])).convert('RGBA')),
composite(base_imgs[pid]), composite(lora_imgs[pid])]
for j, t in enumerate(tiles):
sheet.paste(Image.fromarray(t).resize((cell, cell)), (j * cell, i * cell))
sheet.save(os.path.join(args.out, 'contact_sheet.png'))
results = {'ckpt': args.ckpt, 'audit': audit,
'base_rows': base_rows, 'lora_rows': lora_rows, 'changed': ch,
'mean_changed_train': float(np.mean(tr_ch)) if tr_ch else None,
'mean_changed_eval': float(np.mean(ev_ch)) if ev_ch else None}
with open(os.path.join(args.out, 'gate_results.json'), 'w') as f:
json.dump(results, f, indent=1)
api = HfApi()
for f_ in ('contact_sheet.png', 'gate_results.json'):
try:
api.upload_file(path_or_fileobj=os.path.join(args.out, f_),
path_in_repo=f'eval/gate/{args.ckpt}/{f_}',
repo_id=DS_REPO, repo_type='dataset')
print(f'[upload] {f_} -> eval/gate/{args.ckpt}/ OK', flush=True)
except Exception as e:
print(f'[upload] {f_} FAILED: {e}', flush=True)
# ---- verdict ---------------------------------------------------------
ok_audit = len(b_keys) > 0 and zero_b == 0
ok_change = bool(tr_ch) and min(tr_ch) > 0.02
ok_iou = np.mean([r['alpha_iou'] for r in lora_rows if r['pair_id'] in
train_ids]) > 0.5
if ok_audit and ok_change and ok_iou:
print(f'GATE PASS (audit ok, changed_train mean '
f'{np.mean(tr_ch):.3f}, changed_eval mean '
f'{np.mean(ev_ch):.3f})', flush=True)
else:
print(f'GATE FAIL: audit_ok={ok_audit} change_ok={ok_change} '
f'iou_ok={ok_iou}', flush=True)
if __name__ == '__main__':
main()