"""Measure SADAE's five-target violation; guard checks whether the latest run meets every target.""" import argparse import json import math import os from pathlib import Path import subprocess import sys import tempfile ROOT = Path(__file__).resolve().parents[1] TARGETS = { 'psnr_unedit_part': ('>=', 25.0), 'lpips_unedit_part': ('<=', 0.08), 'mse_unedit_part': ('<=', 0.06), 'clip_similarity_target_image': ('>=', 25.5), 'clip_similarity_target_image_edit_part': ('>=', 23.3), } def git_head(): return subprocess.run( ['git', 'rev-parse', 'HEAD'], cwd=ROOT, check=True, capture_output=True, text=True, ).stdout.strip() def read_summary(path, expected_samples): summary = json.loads(path.read_text(encoding='utf-8')) if summary['count'] != expected_samples: raise ValueError(f'{path}: expected {expected_samples} samples, got {summary["count"]}') statistics = summary['pie_bench_metrics']['statistics'] metrics = {} deficits = [] for name, (operator, limit) in TARGETS.items(): result = statistics[name] if result['count'] != expected_samples: raise ValueError(f'{path}: {name} has {result["count"]}/{expected_samples} valid samples') value = float(result['mean']) if not math.isfinite(value): if name != 'psnr_unedit_part' or value != math.inf: raise ValueError(f'{path}: non-finite {name}={value}') metrics[name] = 'inf' if value == math.inf else value deficit = limit - value if operator == '>=' else value - limit deficits.append(max(0.0, deficit / limit)) metrics['violation'] = math.fsum(deficits) metrics['targets_met'] = metrics['violation'] == 0.0 return metrics def main(): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest='command', required=True) for command in ('verify', 'guard'): subparser = commands.add_parser(command) subparser.add_argument('--output-root', type=Path, default=ROOT / 'result/sadae_autoresearch', help='Shared result directory for verify and guard') if command == 'verify': subparser.add_argument('--dataset', type=Path, default=ROOT / 'data/pie_bench_val30_v1', help='PIE-Bench dataset containing mapping_file.json') subparser.add_argument('--max-samples', type=int, default=0, help='Number of first samples to evaluate; 0 evaluates the entire dataset') subparser.add_argument('--seed', type=int, default=999) args = parser.parse_args() output_root = args.output_root.resolve() latest = output_root / 'latest.json' if args.command == 'verify': if args.max_samples < 0: parser.error('--max-samples must be nonnegative') output_root.mkdir(parents=True, exist_ok=True) # A failed verification must not leave the previous measurement available to guard. latest.unlink(missing_ok=True) dataset = args.dataset.resolve() dataset_samples = len(json.loads((dataset / 'mapping_file.json').read_text(encoding='utf-8'))) if not dataset_samples: raise ValueError(f'{dataset}: dataset is empty') expected_samples = min(args.max_samples, dataset_samples) if args.max_samples else dataset_samples head = git_head() run_dir = Path(tempfile.mkdtemp(prefix='run-', dir=output_root)) sweep_dir = run_dir / 'outputs' log_path = run_dir / 'run.log' command = [ 'bash', str(ROOT / 'scripts/nf_source_anchored_decoupled_affine_editing.sh'), '--dataset', str(dataset), '--start-index', '0', '--max-samples', str(args.max_samples), '--seed', str(args.seed), '--no-training-noise', '--output-dir', str(sweep_dir), ] env = os.environ.copy() env.setdefault('CUDA_VISIBLE_DEVICES', '0,1,2,3') env['NPROC_PER_NODE'] = str(len(env['CUDA_VISIBLE_DEVICES'].split(','))) print(f'Running SADAE; log: {log_path}', file=sys.stderr, flush=True) with log_path.open('x', encoding='utf-8') as log: completed = subprocess.run(command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT) if completed.returncode != 0: raise RuntimeError(f'SADAE exited {completed.returncode}; log: {log_path}') summaries = list(sweep_dir.glob('*/summary.json')) if len(summaries) != 1: raise ValueError(f'Expected exactly one summary.json, got {len(summaries)}; log: {log_path}') summary_path = summaries[0] metrics = read_summary(summary_path, expected_samples) result = { **metrics, 'summary_path': str(summary_path), 'log_path': str(log_path), 'samples': expected_samples, 'dataset': str(dataset), 'seed': args.seed, 'git_head': head, 'cuda_visible_devices': env['CUDA_VISIBLE_DEVICES'], 'training_noise': False, } text = json.dumps(result, allow_nan=False) + '\n' (run_dir / 'evaluation.json').write_text(text, encoding='utf-8') latest.write_text(text, encoding='utf-8') print(text, end='') return 0 result = json.loads(latest.read_text(encoding='utf-8')) if result['git_head'] != git_head(): raise ValueError(f'{latest}: result belongs to a different Git commit; run verify again') metrics = read_summary(Path(result['summary_path']), result['samples']) violations = [] for name, (operator, limit) in TARGETS.items(): value = float(metrics[name]) passed = value >= limit if operator == '>=' else value <= limit if not passed: violations.append(f'{name}={value:g} must be {operator} {limit:g}') print(json.dumps({ **metrics, 'guard_passed': not violations, 'violations': violations, 'summary_path': result['summary_path'], }, allow_nan=False)) return 1 if violations else 0 if __name__ == '__main__': try: sys.exit(main()) except (OSError, ValueError, KeyError, TypeError, RuntimeError, subprocess.CalledProcessError) as exc: print(f'ERROR: {exc}', file=sys.stderr) sys.exit(2)