File size: 11,810 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
"""Mask alignment, metric region semantics and saved evaluation checks."""

from contextlib import redirect_stdout
from io import BytesIO
import io
import json
import math
from pathlib import Path
import sys
import tempfile
from types import ModuleType
import unittest
from unittest.mock import patch

import torch
from PIL import Image
from torchmetrics.functional.image import structural_similarity_index_measure

import pie_bench_metrics as metrics


class FakeClip:
    def __init__(self):
        self.images = []

    def reset(self):
        pass

    def __call__(self, image, prompt):
        self.images.append(image.clone())
        return torch.tensor(25.0)


class FakeLPIPS:
    def __init__(self):
        self.images = []

    def reset(self):
        pass

    def __call__(self, edited, source):
        self.images.append((edited.clone(), source.clone()))
        return torch.tensor(0.125)


class FakeDino(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.blocks = torch.nn.ModuleList([torch.nn.Module()])
        self.blocks[0].attn = torch.nn.Module()
        self.blocks[0].attn.qkv = torch.nn.Linear(3, 18)

    def forward(self, image):
        self.last_image = image.clone()
        return self.blocks[0].attn.qkv(image[:, :, ::56, ::56].flatten(2).transpose(1, 2))


class PieBenchMetricsTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        torch.set_num_threads(1)

    def make_calculator(self):
        from torchvision import transforms

        calculator = metrics.PieBenchMetrics.__new__(metrics.PieBenchMetrics)
        calculator.device = torch.device('cpu')
        calculator.clip = FakeClip()
        calculator.lpips = FakeLPIPS()
        calculator.dino = FakeDino().eval()
        calculator.ssim = structural_similarity_index_measure
        calculator.dino_transform = transforms.Compose([
            transforms.Resize(224, max_size=480),
            transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
        ])
        return calculator

    def test_rle_mask_preserves_region_and_matches_source_crop(self):
        buffer = BytesIO()
        Image.new('RGB', (8, 4)).save(buffer, format='PNG')
        mask = metrics.preprocess_pie_mask('12 1', buffer.getvalue(), 4)
        torch.testing.assert_close(mask, metrics.preprocess_pie_mask([12, 1], buffer.getvalue(), 4))
        # Center crop selects original columns 2..5, so original (y=1,x=4) lands at (1,2).
        expected = torch.tensor([[1, 1, 1, 1], [0, 0, 1, 0],
                                 [0, 0, 0, 0], [1, 1, 1, 1]], dtype=torch.bool)
        torch.testing.assert_close(mask, expected)
        self.assertTrue(metrics.preprocess_pie_mask('0 32', buffer.getvalue(), 4).all())
        resized = metrics.preprocess_pie_mask('12 1', buffer.getvalue(), 2)
        torch.testing.assert_close(resized, torch.tensor([[0, 0], [1, 1]], dtype=torch.bool))
        with self.assertRaises(ValueError):
            metrics.preprocess_pie_mask('12', buffer.getvalue(), 4)

    def test_mask_exif_orientation_matches_image_preprocessing(self):
        buffer = BytesIO()
        image = Image.new('RGB', (8, 4))
        exif = image.getexif()
        exif[274] = 6
        image.save(buffer, format='PNG', exif=exif)
        mask = metrics.preprocess_pie_mask('12 1', buffer.getvalue(), 4)
        expected = torch.tensor([[1, 1, 1, 1], [0, 0, 1, 0],
                                 [0, 0, 0, 0], [1, 1, 1, 1]], dtype=torch.bool)
        torch.testing.assert_close(mask, torch.rot90(expected, -1))

    def test_background_scores_ignore_edit_region_and_use_official_reduction(self):
        calculator = self.make_calculator()
        source = torch.zeros(3, 32, 32, dtype=torch.uint8)
        edited = source.clone()
        mask = torch.zeros(32, 32, dtype=torch.bool)
        mask[:, :16] = True
        edited[:, :, :16] = 255
        edited[:, :, 16:] = 51
        scores = calculator.calculate(source, edited, mask, 'target')
        # Half the pixels have error 0.2; masked pixels contribute zero to the full-image mean.
        self.assertAlmostEqual(scores['mse_unedit_part'], 0.02, places=7)
        self.assertAlmostEqual(scores['psnr_unedit_part'], -10 * math.log10(0.02), places=5)
        self.assertEqual(scores['lpips_unedit_part'], 0.125)
        lpips_edited, lpips_source = calculator.lpips.images[0]
        self.assertTrue((lpips_edited[:, :, :, :16] == -1).all())
        self.assertTrue((lpips_source == -1).all())
        self.assertTrue((calculator.clip.images[1][:, :, 16:] == 0).all())
        torch.testing.assert_close(calculator.clip.images[0], edited)
        edited[:, :, 16:] = 0
        identical_bg = calculator.calculate(source, edited, mask, 'target')
        self.assertEqual(identical_bg['psnr_unedit_part'], 'inf')
        self.assertEqual(identical_bg['mse_unedit_part'], 0)
        self.assertAlmostEqual(identical_bg['ssim_unedit_part'], 1)

    def test_full_and_empty_masks_have_defined_metric_counts(self):
        calculator = self.make_calculator()
        image = torch.zeros(3, 32, 32, dtype=torch.uint8)
        full = calculator.calculate(image, image, torch.ones(32, 32, dtype=torch.bool), 'target')
        empty = calculator.calculate(image, image, torch.zeros(32, 32, dtype=torch.bool), 'target')
        self.assertEqual(full['structure_distance'], 0)
        self.assertTrue(all(full[name] is None for name in metrics.METRIC_NAMES[1:5]))
        self.assertIsNone(empty['clip_similarity_target_image_edit_part'])
        summary = metrics.summarize_metrics([{'pie_bench_metrics': full}, {'pie_bench_metrics': empty}])
        self.assertEqual(summary['mse_unedit_part']['count'], 1)
        self.assertEqual(summary['clip_similarity_target_image_edit_part']['count'], 1)
        self.assertEqual(summary['psnr_unedit_part'], {'mean': 'inf', 'std': None, 'count': 1})
        json.dumps(summary, allow_nan=False)

    def test_dino_keys_match_official_head_concatenation_and_hooks_are_removed(self):
        calculator = self.make_calculator()
        image = torch.randint(0, 256, (3, 32, 32), dtype=torch.uint8)
        actual = calculator.key_self_similarity(image)
        qkv = calculator.dino.blocks[0].attn.qkv(
            calculator.dino.last_image[:, :, ::56, ::56].flatten(2).transpose(1, 2))[0]
        tokens = qkv.shape[0]
        keys = qkv.reshape(tokens, 3, 2, 3).permute(1, 2, 0, 3)[1]
        keys = keys.transpose(0, 1).reshape(tokens, 6)
        norms = keys.norm(dim=1, keepdim=True)
        torch.testing.assert_close(actual, (keys @ keys.T) / (norms @ norms.T).clamp_min(1e-8))
        self.assertGreater(calculator.dino.last_image.max().item(), 100)
        self.assertFalse(calculator.dino.blocks[0].attn.qkv._forward_hooks)
        with patch.object(calculator.dino, 'forward', side_effect=RuntimeError('probe failure')):
            with self.assertRaises(RuntimeError):
                calculator.key_self_similarity(image)
        self.assertFalse(calculator.dino.blocks[0].attn.qkv._forward_hooks)

    def test_dino_hub_imports_are_isolated_from_loaded_project_modules(self):
        import utils as project_utils

        existing_vit = ModuleType('vision_transformer')
        hub_load = torch.hub.load
        with tempfile.TemporaryDirectory() as temporary:
            repo = Path(temporary)
            (repo / 'utils.py').write_text('def trunc_normal_(value):\n    return value + 1\n')
            (repo / 'vision_transformer.py').write_text(
                'import torch\nfrom utils import trunc_normal_\n'
                'class Model(torch.nn.Module):\n'
                '    def forward(self, value):\n        return trunc_normal_(value)\n')
            (repo / 'hubconf.py').write_text(
                'from vision_transformer import Model\n'
                'def dino_vitb8():\n    return Model()\n')
            with patch.dict(sys.modules, {'utils': project_utils, 'vision_transformer': existing_vit}), \
                    patch('torchmetrics.multimodal.CLIPScore', return_value=torch.nn.Identity()), \
                    patch('torchmetrics.image.lpip.LearnedPerceptualImagePatchSimilarity',
                          return_value=torch.nn.Identity()), \
                    patch('torch.hub.load', side_effect=lambda *a, **k: hub_load(
                        str(repo), 'dino_vitb8', source='local')):
                original_path = sys.path.copy()
                for _ in range(2):
                    calculator = metrics.PieBenchMetrics('cpu')
                    self.assertEqual(calculator.dino(torch.tensor(1)).item(), 2)
                    self.assertIs(sys.modules['utils'], project_utils)
                    self.assertIs(sys.modules['vision_transformer'], existing_vit)
                    self.assertEqual(sys.path, original_path)

    def test_dino_load_failure_restores_project_modules(self):
        import utils as project_utils

        existing_vit = ModuleType('vision_transformer')

        def fail_load(*args, **kwargs):
            sys.modules['utils'] = ModuleType('utils')
            sys.modules['vision_transformer'] = ModuleType('vision_transformer')
            raise RuntimeError('DINO load failure')

        with patch.dict(sys.modules, {'utils': project_utils, 'vision_transformer': existing_vit}), \
                patch('torchmetrics.multimodal.CLIPScore', return_value=torch.nn.Identity()), \
                patch('torchmetrics.image.lpip.LearnedPerceptualImagePatchSimilarity',
                      return_value=torch.nn.Identity()), \
                patch('torch.hub.load', side_effect=fail_load):
            with self.assertRaisesRegex(RuntimeError, 'DINO load failure'):
                metrics.PieBenchMetrics('cpu')
            self.assertIs(sys.modules['utils'], project_utils)
            self.assertIs(sys.modules['vision_transformer'], existing_vit)

    def test_saved_results_are_quantized_and_csv_metadata_summary_agree(self):
        calculator = self.make_calculator()
        with tempfile.TemporaryDirectory() as temporary:
            output = Path(temporary)
            reports, masks = [], []
            for image_id, full in (('0', True), ('9', False)):
                for folder in ('source', 'editing', 'metadata'):
                    (output / folder / 'category').mkdir(parents=True, exist_ok=True)
                Image.new('RGB', (32, 32), (100, 120, 130)).save(output / 'source/category' / f'{image_id}.png')
                Image.new('RGB', (32, 32), (110, 120, 130)).save(output / 'editing/category' / f'{image_id}.png')
                reports.append({'category': 'category', 'id': image_id, 'target_prompt': 'target'})
                mask = torch.ones(32, 32, dtype=torch.bool) if full else torch.zeros(32, 32, dtype=torch.bool)
                mask[8:24, 8:24] = True
                masks.append(mask)
            printed = io.StringIO()
            with patch.object(metrics, 'PieBenchMetrics', return_value=calculator), redirect_stdout(printed):
                summary = metrics.evaluate_saved_images(output, reports, masks, 'cpu')
            self.assertIn('valid=1/2', printed.getvalue())
            self.assertIn('psnr_unedit_part=NA', printed.getvalue())
            self.assertEqual(summary['image_resolutions_hw'], [[32, 32]])
            self.assertEqual(summary['statistics']['psnr_unedit_part']['count'], 1)
            saved = json.loads((output / 'metadata/category/0.json').read_text())
            self.assertEqual(saved, reports[0])
            self.assertEqual(len((output / 'metrics.csv').read_text().splitlines()), 3)
            self.assertIn('clip_similarity_target_image_edit_part', (output / 'metrics.csv').read_text())
            json.dumps(summary, allow_nan=False)


if __name__ == '__main__':
    unittest.main()