File size: 11,811 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
#!/usr/bin/env python3
"""CPU checks for optional training noise and official pre-decode denoising."""

from contextlib import nullcontext, redirect_stdout
from io import BytesIO, StringIO
import json
from pathlib import Path
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch

from PIL import Image
import torch

import pie_bench_nf_baseline as baseline


class GaussianFlow(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.forward_inputs = []

    def forward(self, x, y, reverse=False, **kwargs):
        mean = y[:len(x)].reshape(-1, 1, 1, 1)
        if reverse:
            return x + mean
        self.forward_inputs.append(x.detach().clone())
        return x - mean, None, [], [torch.zeros_like(x)]

    def get_loss(self, z, logdets):
        return {'loss': 0.5 * z.square().mean() - sum(ld.mean() for ld in logdets)}


class BaselineNoiseTests(unittest.TestCase):
    def run_baseline(self, output_dir, options=(), sigma=0.3, flow=None):
        buffer = BytesIO()
        Image.new('RGB', (2, 2), (96, 128, 160)).save(buffer, format='PNG')
        rows = [('test', {'id': str(i), 'image': {'bytes': buffer.getvalue()},
                         'source_prompt': str(i * 0.1), 'target_prompt': str(i * 0.1 + 0.2)})
                for i in range(5)]
        model = GaussianFlow().eval() if flow is None else flow
        decoded = []

        def decode(x):
            decoded.append(x.clone())
            return x

        vae = SimpleNamespace(downsample_factor=1, scaling_factor=1, decode=decode,
                              vae=SimpleNamespace(encode=lambda x: SimpleNamespace(
                                  latent_dist=SimpleNamespace(mode=lambda: x))))
        args = SimpleNamespace(img_size=2, txt_size=1, noise_std=sigma, noise_type='gaussian',
                               finetuned_vae='none', vae_adapter=None)
        components = (args, model, vae, None, None, SimpleNamespace(distributed=False), 'cpu')
        argv = ['baseline', '--output-dir', str(output_dir), '--batch-size', '4', *options]
        with (patch.object(sys, 'argv', argv),
              patch.object(baseline, 'iter_examples', return_value=iter(rows)),
              patch.object(baseline, 'load_components', return_value=components),
              patch.object(baseline, 'encode_text', side_effect=lambda enc, tok, captions, size, device:
                           torch.tensor([float(c) if c else 0 for c in captions])[:, None, None]),
              patch.object(torch.cuda, 'is_available', return_value=True),
              patch.object(torch.cuda, 'empty_cache'),
              patch.object(torch, 'autocast', side_effect=lambda *a, **kw: nullcontext()),
              patch.object(torch.Tensor, 'cuda', lambda x: x),
              redirect_stdout(StringIO())):
            baseline.main()
        metadata = [json.loads(p.read_text()) for p in sorted(output_dir.glob('metadata/test/*.json'))]
        return model, decoded, metadata, rows

    def test_default_and_manual_noise_keep_legacy_decode(self):
        for noise_std in (0, 0.2):
            with self.subTest(noise_std=noise_std), tempfile.TemporaryDirectory() as directory:
                options = [] if noise_std == 0 else ['--input-noise-std', str(noise_std)]
                model, decoded, metadata, _ = self.run_baseline(Path(directory), options)
                self.assertFalse(model.training)
                for index, offset in ((0, 0), (3, 4)):
                    clean, reconstructed, edited = decoded[index:index + 3]
                    torch.testing.assert_close(edited, reconstructed + 0.2)
                    if noise_std == 0:
                        torch.testing.assert_close(reconstructed, clean)
                    else:
                        self.assertGreater((reconstructed - clean).abs().max().item(), 0.01)
                self.assertTrue(all(m['input_noise_std'] == noise_std for m in metadata))
                self.assertTrue(all(m['self_denoising_steps'] == 0 for m in metadata))

    def test_config_noise_and_official_gradient_step_with_cfg_and_partial_batch(self):
        for sigma in (0.3, 0.45):
            with self.subTest(sigma=sigma), tempfile.TemporaryDirectory() as directory:
                model, decoded, metadata, _ = self.run_baseline(
                    Path(directory), ['--training-noise'], sigma)
                self.assertFalse(model.training)
                for index, offset in ((0, 0), (3, 4)):
                    clean, reconstructed, edited = decoded[index:index + 3]
                    noise = torch.cat([torch.randn((1, *clean.shape[1:]), generator=torch.Generator().manual_seed(
                        999 + i + sum(map(ord, 'test')))) for i in range(offset, offset + len(clean))])
                    raw = clean + sigma * noise
                    source_mean = torch.arange(offset, offset + len(clean)).reshape(-1, 1, 1, 1) * 0.1
                    expected = raw - sigma ** 2 * (raw - source_mean)
                    torch.testing.assert_close(reconstructed, expected)
                    torch.testing.assert_close(edited, expected + 0.2)
                self.assertEqual(len(metadata), 5)
                self.assertTrue(all(m['input_noise_std'] == sigma for m in metadata))
                self.assertTrue(all(m['self_denoising_steps'] == 1 for m in metadata))
                self.assertLess(max(m['roundtrip_latent_mae'] for m in metadata), 1e-6)

    def test_subtracts_original_noise_from_both_decode_inputs_without_gradients(self):
        for sigma, cfg in ((0.3, 0), (0.3, 3.6), (0.45, 0), (0.45, 3.6)):
            with (self.subTest(sigma=sigma, cfg=cfg), tempfile.TemporaryDirectory() as directory,
                  patch.object(baseline, 'process_denoising', side_effect=AssertionError('Unexpected denoising'))):
                model, decoded, metadata, _ = self.run_baseline(
                    Path(directory), ['--training-noise-subtract', '--edit-cfg', str(cfg)], sigma)
                self.assertFalse(model.training)
                self.assertEqual(len(model.forward_inputs), 4)
                for batch_index, (index, offset) in enumerate(((0, 0), (3, 4))):
                    clean, reconstructed, edited = decoded[index:index + 3]
                    noise = torch.cat([torch.randn((1, *clean.shape[1:]), generator=torch.Generator().manual_seed(
                        999 + i + sum(map(ord, 'test')))) for i in range(offset, offset + len(clean))])
                    torch.testing.assert_close(model.forward_inputs[2 * batch_index], clean + sigma * noise)
                    torch.testing.assert_close(reconstructed, clean)
                    torch.testing.assert_close(edited, clean + 0.2)
                self.assertTrue(all(m['input_noise_std'] == sigma for m in metadata))
                self.assertTrue(all(m['self_denoising_steps'] == 0 for m in metadata))
                self.assertTrue(all(m['subtract_input_noise'] for m in metadata))

    def test_resume_rejects_mixed_noise_and_denoising(self):
        with tempfile.TemporaryDirectory() as directory:
            output_dir = Path(directory)
            _, _, metadata, rows = self.run_baseline(output_dir)
            # Older metadata without the new field must still resume as zero steps.
            for item in metadata:
                item.pop('self_denoising_steps')
                item.pop('subtract_input_noise')
                baseline.output_paths(output_dir, 'test', item['id'])['metadata'].write_text(json.dumps(item))
            self.assertEqual(list(baseline.iter_pending_batches(
                rows, output_dir, 4, 0, False, False, input_noise_std=0,
                self_denoising_steps=0, subtract_input_noise=False)), [])
            with self.assertRaisesRegex(ValueError, 'input_noise_std'):
                list(baseline.iter_pending_batches(
                    rows, output_dir, 4, 0, False, False, input_noise_std=0.3, self_denoising_steps=1))
            with self.assertRaisesRegex(ValueError, 'self_denoising_steps'):
                list(baseline.iter_pending_batches(
                    rows, output_dir, 4, 0, False, False, input_noise_std=0, self_denoising_steps=1))
            with self.assertRaisesRegex(ValueError, 'subtract_input_noise'):
                list(baseline.iter_pending_batches(
                    rows, output_dir, 4, 0, False, False, input_noise_std=0,
                    self_denoising_steps=0, subtract_input_noise=True))

    def test_training_noise_and_manual_scale_are_mutually_exclusive(self):
        for options in (['--training-noise', '--input-noise-std', '0.3'],
                        ['--training-noise-subtract', '--input-noise-std', '0.3'],
                        ['--training-noise-subtract', '--training-noise']):
            with self.subTest(options=options), patch.object(sys, 'argv', ['baseline', *options]):
                with redirect_stdout(StringIO()), patch.object(sys, 'stderr', StringIO()):
                    with self.assertRaises(SystemExit):
                        baseline.parse_args()

    def test_closed_loop_baseline_saves_fp64_z_and_checks_resume_mode(self):
        from transformer_flow import Model
        from nf_roundtrip import closed_loop_reverse

        torch.manual_seed(42)
        model = Model(in_channels=3, img_size=2, patch_size=1, channels=64,
                      num_blocks=2, layers_per_block=[1, 2], head_dim=64,
                      rope=True, sos=True, txt_size=1, txt_dim=1, cond_top_only=True,
                      use_softplus=True, use_final_norm=True, soft_clip=4).eval()
        with torch.no_grad():
            for block in model.blocks:
                block.proj_out.weight.normal_(std=0.045)
        with tempfile.TemporaryDirectory() as directory:
            output_dir = Path(directory)
            _, decoded, metadata, rows = self.run_baseline(
                output_dir, ['--reconstruct-encoder', 'closed-loop', '--reconstruct-cfg', '3.6',
                             '--save-z', '--diagnose-cfg'], flow=model)
            for offset, index in ((0, 0), (4, 3)):
                clean, reconstructed, _ = decoded[index:index + 3]
                torch.testing.assert_close(reconstructed, clean, atol=3e-5, rtol=3e-5)
                batch_rows = rows[offset:offset + len(clean)]
                saved = [torch.load(baseline.output_paths(output_dir, cat, row['id'])['z_reconstruct'],
                                    weights_only=True) for cat, row in batch_rows]
                self.assertTrue(all(z.dtype == torch.float64 for z in saved))
                source = torch.tensor([float(row['source_prompt']) for _, row in batch_rows])[:, None, None]
                condition = torch.cat([source, torch.zeros_like(source)])
                recovered = closed_loop_reverse(model, torch.cat(saved), condition, 3.6)
                torch.testing.assert_close(recovered, reconstructed, atol=0, rtol=0)
            self.assertTrue(all(m['encoder'] == 'closed-loop' for m in metadata))
            self.assertTrue(all(m['reconstruction_z_dtype'] == 'torch.float64' for m in metadata))
            self.assertTrue(all(m['closed_loop_diagnostics']['decoder_vs_simulated_prefix_error']['max_abs'] == 0
                                for m in metadata))
            self.assertEqual(list(baseline.iter_pending_batches(
                rows, output_dir, 4, 0, True, False, reconstruction_encoder='closed-loop',
                diagnose_cfg=True)), [])
            with self.assertRaisesRegex(ValueError, 'reconstruction encoder'):
                list(baseline.iter_pending_batches(
                    rows, output_dir, 4, 0, False, False, reconstruction_encoder='parallel'))


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