File size: 9,543 Bytes
2cf4a54 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | """PIE-Bench metrics following cure-lab/PnPInversion/evaluation.
Scores use saved PNGs and the dataset annotation, at the generated resolution.
"""
import csv
from io import BytesIO
import json
import math
import os
from pathlib import Path
import statistics
import sys
import torch
import torch.nn.functional as F
from PIL import Image, ImageOps
from torchvision import transforms
from torchvision.transforms.functional import pil_to_tensor
METRIC_NAMES = (
'structure_distance', 'psnr_unedit_part', 'lpips_unedit_part',
'mse_unedit_part', 'ssim_unedit_part', 'clip_similarity_target_image',
'clip_similarity_target_image_edit_part',
)
def preprocess_pie_mask(encoded_mask, image_bytes, image_size):
with Image.open(BytesIO(image_bytes)) as raw:
width, height = raw.size
orientation = raw.getexif().get(274, 1)
mask = torch.zeros(height * width, dtype=torch.uint8)
runs = [int(value) for value in (encoded_mask.split() if isinstance(encoded_mask, str) else encoded_mask)]
if len(runs) % 2:
raise ValueError('PIE mask must contain start/length pairs')
for start, length in zip(runs[::2], runs[1::2]):
if start < 0 or length < 0 or start >= mask.numel():
raise ValueError('Invalid PIE mask run')
mask[start:min(start + length, mask.numel())] = 1
mask = mask.reshape(height, width)
# Match the official exclusion of annotation errors at the image boundary.
mask[0, :] = mask[-1, :] = mask[:, 0] = mask[:, -1] = 1
mask = Image.fromarray(mask.numpy())
mask.getexif()[274] = orientation
mask = ImageOps.exif_transpose(mask)
scale = max(image_size / mask.height, image_size / mask.width)
mask = transforms.Resize((int(mask.height * scale), int(mask.width * scale)),
interpolation=transforms.InterpolationMode.NEAREST)(mask)
mask = transforms.CenterCrop((image_size, image_size))(mask)
return pil_to_tensor(mask)[0].bool()
class PieBenchMetrics:
def __init__(self, device):
from torchmetrics.functional.image import structural_similarity_index_measure
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
from torchmetrics.multimodal import CLIPScore
from transformers import CLIPModel, CLIPProcessor
self.device = torch.device(device)
cache_root = Path(__file__).resolve().parents[1] / 'ckpts'
if 'TORCH_HOME' not in os.environ:
torch.hub.set_dir(str(cache_root / 'torch_hub'))
hf_cache = os.environ.get('HF_HUB_CACHE', str(cache_root / 'hf_cache'))
clip_name = 'openai/clip-vit-large-patch14'
self.clip = CLIPScore(model_name_or_path=lambda: (
CLIPModel.from_pretrained(clip_name, cache_dir=hf_cache),
CLIPProcessor.from_pretrained(clip_name, cache_dir=hf_cache, use_fast=False),
)).to(self.device).eval().requires_grad_(False)
self.lpips = LearnedPerceptualImagePatchSimilarity(net_type='squeeze').to(
self.device).eval().requires_grad_(False)
# DINO's top-level imports collide with STARFlow's utils package.
module_names = ('utils', 'vision_transformer')
saved_modules = {name: sys.modules.pop(name) for name in module_names if name in sys.modules}
try:
self.dino = torch.hub.load('facebookresearch/dino:main', 'dino_vitb8', trust_repo=True)
finally:
for name in module_names:
sys.modules.pop(name, None)
sys.modules.update(saved_modules)
self.dino = self.dino.to(self.device).eval().requires_grad_(False)
self.ssim = structural_similarity_index_measure
self.dino_transform = transforms.Compose([
transforms.Resize(224, max_size=480),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
])
def key_self_similarity(self, image):
projections = []
hook = self.dino.blocks[-1].attn.qkv.register_forward_hook(
lambda module, inputs, output: projections.append(output))
try:
# The official implementation feeds DINO 0..255 floats, without /255.
self.dino(self.dino_transform(image.float().unsqueeze(0)))
finally:
hook.remove()
keys = projections[0][0].chunk(3, dim=-1)[1]
norms = keys.norm(dim=-1, keepdim=True)
return (keys @ keys.T) / (norms @ norms.T).clamp_min(1e-8)
@torch.no_grad()
def calculate(self, source, edited, mask, target_prompt):
if source.shape != edited.shape or mask.shape != source.shape[-2:]:
raise ValueError('Source, edited image and PIE mask must be aligned')
source, edited, mask = (value.to(self.device) for value in (source, edited, mask))
scores = dict.fromkeys(METRIC_NAMES)
scores['structure_distance'] = F.mse_loss(
self.key_self_similarity(source), self.key_self_similarity(edited)).item()
self.clip.reset()
scores['clip_similarity_target_image'] = self.clip(edited, target_prompt).item()
if mask.any():
self.clip.reset()
scores['clip_similarity_target_image_edit_part'] = self.clip(
edited * mask, target_prompt).item()
if (~mask).any():
background = (~mask).float()
source_bg = (source.float() / 255 * background).unsqueeze(0)
edited_bg = (edited.float() / 255 * background).unsqueeze(0)
# Official metrics zero the edit region and average over the full image.
mse = F.mse_loss(edited_bg, source_bg).item()
scores['mse_unedit_part'] = mse
scores['psnr_unedit_part'] = -10 * math.log10(mse) if mse else 'inf'
self.lpips.reset()
scores['lpips_unedit_part'] = self.lpips(edited_bg * 2 - 1, source_bg * 2 - 1).item()
scores['ssim_unedit_part'] = self.ssim(edited_bg, source_bg, data_range=1.0).item()
for name, value in scores.items():
if isinstance(value, float) and not math.isfinite(value):
raise FloatingPointError(f'Non-finite PIE metric: {name}={value}')
return scores
def summarize_metrics(reports):
summary = {}
for name in METRIC_NAMES:
values = [float(report['pie_bench_metrics'][name]) for report in reports
if report['pie_bench_metrics'][name] is not None]
mean = statistics.mean(values) if values else None
summary[name] = {
'mean': 'inf' if mean == math.inf else mean,
'std': statistics.pstdev(values) if values and all(math.isfinite(v) for v in values) else None,
'count': len(values),
}
return summary
def evaluate_saved_images(output_dir, reports, masks, device):
print(f'Evaluating PIE-Bench metrics on {device} ({len(reports)} images)', flush=True)
calculator = PieBenchMetrics(device)
resolutions = set()
with (output_dir / 'metrics.csv').open('x', newline='') as handle:
writer = csv.DictWriter(handle, fieldnames=['category', 'id', *METRIC_NAMES])
writer.writeheader()
for report, mask in zip(reports, masks, strict=True):
stem = Path(report['category']) / report['id']
filename = stem.with_name(stem.name + '.png')
with Image.open(output_dir / 'source' / filename) as image:
source = pil_to_tensor(image.convert('RGB'))
with Image.open(output_dir / 'editing' / filename) as image:
edited = pil_to_tensor(image.convert('RGB'))
resolutions.add(tuple(source.shape[-2:]))
scores = calculator.calculate(source, edited, mask, report['target_prompt'])
report['pie_bench_metrics'] = scores
report['pie_bench_mask_fraction'] = mask.float().mean().item()
(output_dir / 'metadata' / stem.with_name(stem.name + '.json')).write_text(
json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False) + '\n')
writer.writerow({'category': report['category'], 'id': report['id'], **scores})
handle.flush()
formatted = ', '.join(f'{name}={"NA" if value is None else format(value, ".6g") if isinstance(value, float) else value}'
for name, value in scores.items())
print(f' {stem}: {formatted}', flush=True)
summary = summarize_metrics(reports)
print('PIE-Bench mean (raw scores; CLIP is on the 0..100 scale):', flush=True)
for name, result in summary.items():
value = result['mean']
formatted = 'NA' if value is None else format(value, '.6g') if isinstance(value, float) else value
print(f' {name}={formatted}; valid={result["count"]}/{len(reports)}', flush=True)
return {
'implementation': 'https://github.com/cure-lab/PnPInversion/tree/main/evaluation',
'mask': 'dataset annotation; boundary exclusion; nearest resize and source center crop',
'image_resolutions_hw': [list(size) for size in sorted(resolutions)],
'dino': 'dino_vitb8; final-block key self-similarity MSE; official 0..255 input',
'lpips': 'squeeze', 'clip': 'openai/clip-vit-large-patch14; 100 * max(cosine, 0)',
'background': 'edit region zeroed; full-image metric reduction',
'undefined': 'null for empty regions; string inf for zero-error PSNR',
'std': 'population standard deviation; null if undefined or infinite',
'statistics': summary,
}
|