Download scripts/test_nf_source_anchored_decoupled_affine_editing.py from Lingmin-Ran/SADAE: direct link, hf CLI and curl.
- Browser
- Download file 46.2 kB
-
https://huggingface.co/Lingmin-Ran/SADAE/resolve/main/scripts/test_nf_source_anchored_decoupled_affine_editing.py
- Command line
-
hf download hf://Lingmin-Ran/SADAE/scripts/test_nf_source_anchored_decoupled_affine_editing.py
-
curl -L -o test_nf_source_anchored_decoupled_affine_editing.py https://huggingface.co/Lingmin-Ran/SADAE/resolve/main/scripts/test_nf_source_anchored_decoupled_affine_editing.py
46.2 kB
| #!/usr/bin/env python3 | |
| """Numerical SADAE-v2 and compatibility checks with small StarFlow models.""" | |
| from contextlib import nullcontext, redirect_stderr, redirect_stdout | |
| import io | |
| from itertools import product | |
| import json | |
| import os | |
| from pathlib import Path | |
| import subprocess | |
| import sys | |
| import tempfile | |
| from types import SimpleNamespace | |
| import unittest | |
| from unittest.mock import Mock, patch | |
| import torch | |
| import torch.nn.functional as F | |
| import nf_source_anchored_decoupled_affine_editing as editing | |
| from transformer_flow import IdentityBlock, INV_SOFTPLUS_1, Model | |
| from nf_roundtrip import closed_loop_forward, closed_loop_reverse | |
| class SADAEtests(unittest.TestCase): | |
| def setUpClass(cls): | |
| torch.set_num_threads(1) | |
| cls.device = torch.device(os.environ.get('SADAE_TEST_DEVICE', 'cpu')) | |
| def make_model(self, order='L2R', sos=True, softplus=True, patch_size=1, identity=False): | |
| torch.manual_seed(12) | |
| model = Model(in_channels=2, img_size=4, patch_size=patch_size, channels=32, | |
| num_blocks=3, layers_per_block=[0 if identity else 1, 1, 2], head_dim=32, | |
| rope=True, sos=sos, txt_size=3, txt_dim=8, cond_top_only=True, | |
| use_softplus=softplus, use_final_norm=True, soft_clip=4, seq_order=order) | |
| with torch.no_grad(): | |
| for block in model.blocks: | |
| if not isinstance(block, IdentityBlock): | |
| block.proj_out.weight.normal_(std=0.04) | |
| block.proj_out.bias.normal_(std=0.03) | |
| return model.to(self.device).eval().requires_grad_(False) | |
| def inputs(self): | |
| return (torch.randn(1, 2, 4, 4, device=self.device), | |
| torch.randn(1, 3, 8, device=self.device), torch.randn(1, 3, 8, device=self.device)) | |
| def test_cached_edit_matches_full_teacher_forcing_oracle(self): | |
| configurations = ( | |
| ('L2R', True, True, 1), ('R2L', False, False, 2), | |
| ('R2L', True, False, 1), ('L2R', False, True, 2)) | |
| for (order, sos, softplus, patch_size), gamma in product(configurations, (0.0, 0.35, 1.0)): | |
| with self.subTest(order=order, sos=sos, softplus=softplus, gamma=gamma): | |
| model = self.make_model(order, sos, softplus, patch_size) | |
| source, cs, ct = self.inputs() | |
| _, _, states, _ = model(source, cs, guidance=0) | |
| top = model.blocks[-1] | |
| original = top.permutation(states[-2]) | |
| noise = top.permutation(states[-1]) | |
| target_noise, _, target_logdet = top(states[-2], ct, model.feat_rope_gen) | |
| # Recover d0 independently from the NF output and its log determinant. | |
| fixed_delta = (-target_logdet).exp() * (noise - top.permutation(target_noise)) | |
| expected = original.clone() | |
| alpha, beta = 1.3, 0.4 | |
| # Full-sequence teacher forcing independently recomputes both affines. | |
| for slot in range(0 if sos else 1, noise.shape[1]): | |
| candidates = [] | |
| for condition in (cs, ct): | |
| projections = [] | |
| hook = top.proj_out.register_forward_hook( | |
| lambda module, args, output: projections.append(output.detach())) | |
| try: | |
| top(top.permutation(expected, inverse=True), condition, model.feat_rope_gen) | |
| finally: | |
| hook.remove() | |
| raw = projections[0] | |
| raw = top.soft_clip * torch.tanh(raw / top.soft_clip) | |
| raw = raw[:, slot:slot + 1] if sos else raw[:, slot - 1:slot] | |
| raw_scale, mean = raw.chunk(2, -1) | |
| scale = F.softplus(raw_scale + INV_SOFTPLUS_1) if softplus else raw_scale.exp() | |
| candidates.append(mean + scale * noise[:, slot:slot + 1]) | |
| s, t = candidates | |
| r = original[:, slot:slot + 1] | |
| if gamma == 1.0: | |
| expected[:, slot:slot + 1] = r + alpha * (t - s) + beta * (s - r) | |
| else: | |
| d0 = fixed_delta[:, slot:slot + 1] | |
| expected[:, slot:slot + 1] = r + alpha * d0 + beta * (s - r) + alpha * gamma * ((t - s) - d0) | |
| observed = [] | |
| reverse_step = top.reverse_step | |
| def record(generated, step, cache, *args, **kwargs): | |
| slot = step if sos else step + 1 | |
| observed.append((slot, generated[:, :slot].clone(), cache)) | |
| return reverse_step(generated, step, cache, *args, **kwargs) | |
| with patch.object(top, 'reverse_step', side_effect=record): | |
| edited, artifacts, report = editing.edit_latent( | |
| model, source, cs, ct, alpha, beta, False, gamma=gamma) | |
| torch.testing.assert_close(artifacts['h_edit'], expected, atol=3e-6, rtol=3e-6) | |
| torch.testing.assert_close(artifacts['h_source'], original, atol=0, rtol=0) | |
| torch.testing.assert_close(artifacts['z_source'], noise, atol=0, rtol=0) | |
| torch.testing.assert_close(artifacts['d0'], fixed_delta, atol=3e-6, rtol=3e-6) | |
| torch.testing.assert_close(artifacts['q'], artifacts['d'] - artifacts['d0'], | |
| atol=0, rtol=0) | |
| if gamma == 1.0: | |
| torch.testing.assert_close(artifacts['h_edit'], | |
| original + alpha * artifacts['d'] + beta * artifacts['b'], | |
| atol=0, rtol=0) | |
| else: | |
| torch.testing.assert_close(artifacts['h_edit'], | |
| original + alpha * artifacts['d0'] + beta * artifacts['b'] | |
| + alpha * gamma * artifacts['q'], atol=0, rtol=0) | |
| self.assertEqual(report['gamma'], gamma) | |
| self.assertGreater(artifacts['q'].abs().max().item(), 1e-6) | |
| if not sos: | |
| torch.testing.assert_close(artifacts['h_edit'][:, :1], original[:, :1], atol=0, rtol=0) | |
| for slot, prefix, cache in observed: | |
| torch.testing.assert_close(prefix, artifacts['h_edit'][:, :slot], atol=0, rtol=0) | |
| self.assertTrue(cache.is_empty) | |
| self.assertIsNot(observed[0][2], observed[1][2]) | |
| self.assertGreater((edited - source).abs().max().item(), 1e-5) | |
| def test_same_condition_and_zero_text_weight_reconstruct_source(self): | |
| for order, sos, patch_size, identity in (('L2R', True, 1, False), ('R2L', False, 2, True)): | |
| model = self.make_model(order=order, sos=sos, patch_size=patch_size, identity=identity) | |
| source, cs, ct = self.inputs() | |
| for (alpha, beta), gamma in product(((0.0, 0.0), (1.0, 0.5), (2.0, 1.0)), (0.0, 0.35, 1.0)): | |
| edited, artifacts, report = editing.edit_latent( | |
| model, source, cs, cs, alpha, beta, False, gamma=gamma) | |
| torch.testing.assert_close(edited, source, atol=3e-6, rtol=3e-6) | |
| torch.testing.assert_close(artifacts['d'], torch.zeros_like(artifacts['d']), atol=0, rtol=0) | |
| torch.testing.assert_close(artifacts['d0'], torch.zeros_like(artifacts['d0']), atol=3e-6, rtol=0) | |
| torch.testing.assert_close(artifacts['q'], torch.zeros_like(artifacts['q']), atol=3e-6, rtol=0) | |
| self.assertLess(report['latent_displacement_max_abs'], 3e-6) | |
| for beta, gamma in product((0.0, 0.5, 1.0), (0.0, 0.35, 1.0)): | |
| edited, _, _ = editing.edit_latent(model, source, cs, ct, 0.0, beta, False, gamma=gamma) | |
| torch.testing.assert_close(edited, source, atol=3e-6, rtol=3e-6) | |
| def test_zero_prefix_and_interaction_weights_use_fixed_reference(self): | |
| for order, sos, softplus, patch_size in (('L2R', True, True, 1), ('R2L', False, False, 2)): | |
| model = self.make_model(order, sos, softplus, patch_size) | |
| source, cs, ct = self.inputs() | |
| _, artifacts, _ = editing.edit_latent(model, source, cs, ct, 1.3, 0.0, False, gamma=0.0) | |
| torch.testing.assert_close(artifacts['h_edit'], artifacts['h_source'] + 1.3 * artifacts['d0'], | |
| atol=0, rtol=0) | |
| def test_cfg_saved_noise_and_identity_match_closed_loop(self): | |
| for order, sos, softplus, patch_size in ( | |
| ('L2R', True, True, 1), ('R2L', False, False, 2), | |
| ('R2L', True, False, 1), ('L2R', False, True, 2)): | |
| model = self.make_model(order, sos, softplus, patch_size) | |
| source, cs, ct = self.inputs() | |
| cu = torch.randn_like(cs) | |
| for cfg in (3.6, 7.2): | |
| condition = torch.cat([cs, cu]) | |
| expected_z, _, simulated = closed_loop_forward(model, source, condition, cfg) | |
| expected = closed_loop_reverse(model, expected_z, condition, cfg, return_sequence=True) | |
| top = model.blocks[-1] | |
| for alpha, beta, gamma, target in ( | |
| (0.0, 0.5, 0.35, ct), (1.5, 0.4, 0.0, cs), (2.0, 1.0, 1.0, cs)): | |
| with self.subTest(order=order, sos=sos, cfg=cfg, alpha=alpha, gamma=gamma): | |
| edited, artifacts, report = editing.edit_latent( | |
| model, source, cs, target, alpha, beta, False, | |
| gamma=gamma, cfg=cfg, empty_condition=cu) | |
| self.assertEqual(artifacts['z_source'].dtype, torch.float64) | |
| self.assertEqual(artifacts['h_source'].dtype, torch.float32) | |
| self.assertEqual(artifacts['h_edit'].dtype, torch.float64) | |
| self.assertEqual(edited.dtype, torch.float32) | |
| torch.testing.assert_close(edited, expected[-1], atol=0, rtol=0) | |
| torch.testing.assert_close(artifacts['h_reference'], | |
| top.permutation(model.patchify(expected[1])), atol=0, rtol=0) | |
| torch.testing.assert_close(artifacts['h_edit'], artifacts['h_reference'], atol=0, rtol=0) | |
| self.assertEqual(report['reference_feedback_max_abs'], 0) | |
| self.assertEqual(report['source_encoder'], 'closed-loop') | |
| buffer = io.BytesIO() | |
| torch.save(artifacts['z_source'], buffer) | |
| buffer.seek(0) | |
| loaded = torch.load(buffer, weights_only=True) | |
| z = model.unpatchify(top.permutation(loaded, inverse=True)) | |
| torch.testing.assert_close(z, expected_z, atol=0, rtol=0) | |
| sequence = closed_loop_reverse(model, z, condition, cfg, return_sequence=True) | |
| torch.testing.assert_close(sequence[1].float(), simulated, atol=0, rtol=0) | |
| torch.testing.assert_close(sequence[-1], source, atol=3e-6, rtol=3e-6) | |
| def test_cfg_fixed_reference_and_mixed_updates(self): | |
| for sos, softplus, patch_size in ((True, True, 1), (False, False, 2)): | |
| model = self.make_model(sos=sos, softplus=softplus, patch_size=patch_size) | |
| source, cs, ct = self.inputs() | |
| cu, cfg = torch.randn_like(cs), 3.6 | |
| z, _, simulated = closed_loop_forward(model, source, torch.cat([cs, cu]), cfg) | |
| source_sequence = closed_loop_reverse(model, z, torch.cat([cs, cu]), cfg, return_sequence=True) | |
| top = model.blocks[-1] | |
| original_step = top.reverse_step | |
| known = top.permutation(model.patchify(simulated)) | |
| fixed_prefix = torch.cat([known, known]) | |
| def force_reference(prefix, step, cache, *args, **kwargs): | |
| return original_step(fixed_prefix, step, cache, *args, **kwargs) | |
| # Independently decode target with the encoder's fixed feedback prefix. | |
| with patch.object(top, 'reverse_step', side_effect=force_reference): | |
| target_sequence = closed_loop_reverse(model, z, torch.cat([ct, cu]), cfg, return_sequence=True) | |
| expected_delta = top.permutation(model.patchify(target_sequence[1] - source_sequence[1])) | |
| for beta, gamma in ((0.4, 0.0), (0.4, 0.35), (0.4, 1.0), (0.0, 0.0)): | |
| _, artifacts, _ = editing.edit_latent( | |
| model, source, cs, ct, 1.5, beta, False, gamma=gamma, cfg=cfg, empty_condition=cu) | |
| torch.testing.assert_close(artifacts['d0'], expected_delta, atol=0, rtol=0) | |
| torch.testing.assert_close(artifacts['q'], artifacts['d'] - artifacts['d0'], atol=0, rtol=0) | |
| expected = (artifacts['h_reference'] + 1.5 * artifacts['d0'] + beta * artifacts['b'] | |
| + 1.5 * gamma * artifacts['q']) | |
| torch.testing.assert_close(artifacts['h_edit'], expected, atol=1e-13, rtol=1e-13) | |
| self.assertGreater(artifacts['q'].abs().max().item(), 1e-6) | |
| def test_cfg_unit_weights_match_closed_loop_target_and_share_prefix(self): | |
| for order, sos, softplus, patch_size in ( | |
| ('L2R', True, True, 1), ('R2L', False, False, 2)): | |
| model = self.make_model(order, sos, softplus, patch_size) | |
| source, cs, ct = self.inputs() | |
| cu, cfg = torch.randn_like(cs), 7.2 | |
| top = model.blocks[-1] | |
| original_step, observed = top.reverse_step, [] | |
| def record(prefix, step, cache, *args, **kwargs): | |
| slot = step if sos else step + 1 | |
| observed.append((slot, prefix[:, :slot].clone(), cache)) | |
| self.assertEqual(prefix.dtype, torch.float32) | |
| self.assertEqual(prefix.shape[0], 2) | |
| return original_step(prefix, step, cache, *args, **kwargs) | |
| with patch.object(top, 'reverse_step', side_effect=record): | |
| edited, artifacts, _ = editing.edit_latent( | |
| model, source, cs, ct, 1.0, 1.0, False, cfg=cfg, empty_condition=cu) | |
| z = model.unpatchify(top.permutation(artifacts['z_source'], inverse=True)) | |
| expected = closed_loop_reverse(model, z, torch.cat([ct, cu]), cfg, return_sequence=True) | |
| torch.testing.assert_close(edited, expected[-1], atol=0, rtol=0) | |
| torch.testing.assert_close(artifacts['h_edit'], top.permutation(model.patchify(expected[1])), | |
| atol=0, rtol=0) | |
| steps = artifacts['z_source'].shape[1] - (not sos) | |
| dynamic = observed[-2 * steps:] | |
| self.assertIsNot(dynamic[0][2], dynamic[1][2]) | |
| for slot, prefix, cache in dynamic: | |
| torch.testing.assert_close(prefix[:1], artifacts['h_edit'][:, :slot].float(), atol=0, rtol=0) | |
| torch.testing.assert_close(prefix[1:], prefix[:1], atol=0, rtol=0) | |
| self.assertTrue(cache.is_empty) | |
| def test_cfg_cache_cleanup_on_reference_and_generation_failure(self): | |
| model = self.make_model() | |
| source, cs, ct = self.inputs() | |
| cu = torch.randn_like(cs) | |
| top = model.blocks[-1] | |
| initialize, original_step = top.initialize_kv_cache, top.reverse_step | |
| for stage in (3, 5): | |
| caches = [] | |
| def record(cache, *args, **kwargs): | |
| caches.append(cache) | |
| return initialize(cache, *args, **kwargs) | |
| def fail(prefix, step, cache, *args, **kwargs): | |
| if len(caches) == stage: | |
| raise RuntimeError('CFG prediction failure') | |
| return original_step(prefix, step, cache, *args, **kwargs) | |
| with patch.object(top, 'initialize_kv_cache', side_effect=record), \ | |
| patch.object(top, 'reverse_step', side_effect=fail): | |
| with self.assertRaisesRegex(RuntimeError, 'CFG prediction failure'): | |
| editing.edit_latent(model, source, cs, ct, verbose=False, cfg=3.6, empty_condition=cu) | |
| self.assertEqual(len(caches), stage) | |
| self.assertTrue(all(cache.is_empty for cache in caches)) | |
| def test_unit_weights_match_official_unguided_target_inverse(self): | |
| for order, sos, softplus, patch_size, identity in ( | |
| ('L2R', True, True, 1, False), ('R2L', False, False, 2, True)): | |
| model = self.make_model(order, sos, softplus, patch_size, identity) | |
| source, cs, ct = self.inputs() | |
| z, _, _, _ = model(source, cs, guidance=0) | |
| expected = model(z, ct, reverse=True, guidance=0, jacobi=False) | |
| edited, _, _ = editing.edit_latent(model, source, cs, ct, 1.0, 1.0, False) | |
| torch.testing.assert_close(edited, expected, atol=3e-6, rtol=3e-6) | |
| def test_cache_cleanup_on_prediction_failure(self): | |
| model = self.make_model() | |
| source, cs, ct = self.inputs() | |
| caches = [] | |
| initialize = model.blocks[-1].initialize_kv_cache | |
| def record(cache, *args, **kwargs): | |
| caches.append(cache) | |
| return initialize(cache, *args, **kwargs) | |
| with patch.object(model.blocks[-1], 'initialize_kv_cache', side_effect=record), \ | |
| patch.object(model.blocks[-1], 'reverse_step', side_effect=RuntimeError('test failure')): | |
| with self.assertRaisesRegex(RuntimeError, 'test failure'): | |
| editing.edit_latent(model, source, cs, ct, verbose=False) | |
| self.assertEqual(len(caches), 2) | |
| self.assertTrue(all(cache.is_empty for cache in caches)) | |
| def test_teacher_forcing_hook_cleanup_on_failure(self): | |
| model = self.make_model() | |
| source, cs, ct = self.inputs() | |
| top = model.blocks[-1] | |
| forward = top.forward | |
| hooks = dict(top.proj_out._forward_hooks) | |
| def fail_target(state, condition, *args, **kwargs): | |
| if condition is ct: | |
| raise RuntimeError('teacher-forcing failure') | |
| return forward(state, condition, *args, **kwargs) | |
| with patch.object(top, 'forward', side_effect=fail_target): | |
| with self.assertRaisesRegex(RuntimeError, 'teacher-forcing failure'): | |
| editing.edit_latent(model, source, cs, ct, verbose=False, gamma=0.35) | |
| self.assertEqual(dict(top.proj_out._forward_hooks), hooks) | |
| def test_cli_defaults_and_weight_validation(self): | |
| with patch.object(sys, 'argv', ['editing']): | |
| cli = editing.parse_args() | |
| self.assertEqual((cli.alpha, cli.beta, cli.max_samples, cli.comparison_samples), (1.0, 0.5, 4, 4)) | |
| self.assertEqual(cli.gamma, 1.0) | |
| self.assertEqual(cli.cfg, 0.0) | |
| self.assertEqual(cli.precision, 'fp32') | |
| self.assertFalse(cli.training_noise) | |
| self.assertFalse(cli.skip_metrics) | |
| self.assertEqual(cli.metrics_device, 'cuda') | |
| with patch.object(sys, 'argv', ['editing']), patch.dict(os.environ, {'WORLD_SIZE': '4'}): | |
| self.assertEqual(editing.parse_args().precision, 'fp32') | |
| for flags in (['--alpha', '-1'], ['--alpha', 'nan'], ['--beta', '1.1'], | |
| ['--beta', 'nan'], ['--beta', '-0.1'], ['--max-samples', '-1'], | |
| ['--gamma', 'nan'], ['--gamma', 'inf'], ['--gamma', '-0.1'], ['--gamma', '1.1'], | |
| ['--cfg', 'nan'], ['--cfg', 'inf'], ['--cfg', '-0.1'], | |
| ['--comparison-samples', '0'], ['--comparison-samples', '-1']): | |
| with patch.object(sys, 'argv', ['editing', *flags]), redirect_stderr(io.StringIO()): | |
| with self.assertRaises(SystemExit): | |
| editing.parse_args() | |
| model = self.make_model() | |
| source, cs, ct = self.inputs() | |
| for gamma in (float('nan'), float('inf'), -0.1, 1.1): | |
| with self.assertRaisesRegex(ValueError, 'gamma'): | |
| editing.edit_latent(model, source, cs, ct, verbose=False, gamma=gamma) | |
| for cfg in (float('nan'), float('inf'), -0.1): | |
| with self.assertRaisesRegex(ValueError, 'cfg'): | |
| editing.edit_latent(model, source, cs, ct, verbose=False, cfg=cfg) | |
| for empty in (None, torch.zeros_like(cs)[:, :1]): | |
| with self.assertRaisesRegex(ValueError, 'empty condition'): | |
| editing.edit_latent(model, source, cs, ct, verbose=False, cfg=3.6, empty_condition=empty) | |
| def test_single_image_pipeline_and_existing_output_protection(self): | |
| from PIL import Image | |
| # Keep torchvision's registered operators loaded across sys.modules patches. | |
| import torchvision.transforms | |
| class FakeVAE(torch.nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| self.scaling_factor, self.downsample_factor = 1, 1 | |
| self.decode_dtypes = [] | |
| self.vae = SimpleNamespace(encode=lambda image: SimpleNamespace( | |
| latent_dist=SimpleNamespace(mode=lambda: (image[:, :2] * 0.5).bfloat16()))) | |
| def decode(self, latent): | |
| self.decode_dtypes.append(latent.dtype) | |
| return torch.cat([latent, latent[:, :1]], 1) | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| image_path = root / 'input.v1.png' | |
| Image.new('RGB', (6, 4), (180, 100, 80)).save(image_path) | |
| model = self.make_model(patch_size=2).cpu() | |
| conditions = torch.randn(3, 3, 8) | |
| components = (SimpleNamespace(img_size=4, txt_size=3, cond_noise_level=0), model, | |
| FakeVAE(), None, torch.nn.Identity(), SimpleNamespace(distributed=False), | |
| torch.device('cpu')) | |
| mocks = {'pie_bench_nf_components': SimpleNamespace(load_components=lambda cli: components), | |
| 'utils': SimpleNamespace(encode_text=lambda *args, **kwargs: conditions[:len(args[2])])} | |
| for cfg in (0.0, 3.6): | |
| output = root / f'output_cfg_{cfg}' | |
| components[2].decode_dtypes.clear() | |
| argv = ['editing', '--image-path', str(image_path), '--source-prompt', 'source', | |
| '--target-prompt', 'target', '--gamma', '0.35', '--cfg', str(cfg), | |
| '--output-dir', str(output)] | |
| with patch.dict(sys.modules, mocks), patch.object(sys, 'argv', argv), \ | |
| patch.dict(os.environ, {'WORLD_SIZE': '1'}), \ | |
| patch.object(torch.cuda, 'is_available', return_value=True), \ | |
| patch.object(torch.cuda, 'get_device_name', return_value='CPU test'), \ | |
| patch.object(torch, 'autocast', side_effect=lambda *a, **k: nullcontext()), \ | |
| redirect_stdout(io.StringIO()): | |
| editing.main() | |
| with self.assertRaises(FileExistsError): | |
| editing.main() | |
| saved = torch.load(output / 'states/single/input.v1.pt', weights_only=True) | |
| self.assertNotIn('u_source_clean', saved) | |
| self.assertNotIn('u_edit_denoised', saved) | |
| self.assertEqual(saved['h_source'].shape, (1, 4, 8)) | |
| self.assertEqual(saved['u_edit'].shape, (1, 2, 4, 4)) | |
| reference = saved['h_reference'] if cfg else saved['h_source'] | |
| torch.testing.assert_close(saved['h_edit'], reference + saved['d0'] + 0.5 * saved['b'] | |
| + 0.35 * saved['q'], atol=0, rtol=0) | |
| self.assertEqual(saved['z_source'].dtype, torch.float64 if cfg else torch.float32) | |
| decode_dtype = torch.bfloat16 if cfg else torch.float32 | |
| self.assertEqual(components[2].decode_dtypes, [decode_dtype, decode_dtype]) | |
| for folder in ('source', 'vae_only', 'editing'): | |
| with Image.open(output / folder / 'single/input.v1.png') as preview: | |
| self.assertEqual(preview.size, (4, 4)) | |
| config = json.loads((output / 'run_config.json').read_text()) | |
| self.assertEqual(config['cfg'], cfg) | |
| self.assertEqual(config['source_encoder'], 'closed-loop' if cfg else 'parallel') | |
| self.assertEqual(config['affine_precision'], 'fp64' if cfg else 'fp32') | |
| self.assertEqual(config['method'], 'SADAE') | |
| self.assertEqual(config['method_version'], 2) | |
| self.assertEqual(config['gamma'], 0.35) | |
| self.assertFalse(config['training_noise']) | |
| self.assertEqual(config['self_denoising_steps'], 0) | |
| self.assertNotIn('input_noise_std', config) | |
| self.assertFalse(config['spatial_mask']) | |
| self.assertEqual(json.loads((output / 'summary.json').read_text())['count'], 1) | |
| report = json.loads((output / 'metadata/single/input.v1.json').read_text()) | |
| self.assertNotIn('noise_seed', report) | |
| self.assertEqual(report['token_shape'], list(saved['h_source'].shape)) | |
| self.assertEqual(report['gamma'], 0.35) | |
| self.assertEqual(report['cfg'], cfg) | |
| self.assertEqual(report['vae_decode_dtype'], str(decode_dtype)) | |
| for field, name in (('fixed_text_delta_rms', 'd0'), ('interaction_delta_rms', 'q')): | |
| self.assertEqual(report[field], saved[name].double().square().mean().sqrt().item()) | |
| with Image.open(output / 'comparison.png') as comparison: | |
| self.assertEqual(comparison.size, (8, 36)) | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| dataset = root / 'dataset/category' | |
| dataset.mkdir(parents=True) | |
| rows = [] | |
| for index, image_id in enumerate(('9', '1', '8', '2', '7', '3')): | |
| buffer = io.BytesIO() | |
| Image.new('RGB', (4, 4), (40 + 20 * index, 100, 80)).save(buffer, format='PNG') | |
| rows.append({'image': {'bytes': buffer.getvalue()}, 'id': image_id, | |
| 'source_prompt': 'source', 'target_prompt': 'target'}) | |
| pq.write_table(pa.Table.from_pylist(rows), dataset / 'data.parquet') | |
| for name, flags, count, preview_count in ( | |
| ('default', [], 4, 4), | |
| ('first_two', ['--max-samples', '6', '--comparison-samples', '2'], 6, 2), | |
| ('fewer_than_n', ['--max-samples', '0', '--comparison-samples', '10'], 6, 6)): | |
| output = root / name | |
| argv = ['editing', '--dataset', str(root / 'dataset'), '--skip-metrics', | |
| '--output-dir', str(output), *flags] | |
| with patch.dict(sys.modules, mocks), patch.object(sys, 'argv', argv), \ | |
| patch.dict(os.environ, {'WORLD_SIZE': '1'}), \ | |
| patch.object(torch.cuda, 'is_available', return_value=True), \ | |
| patch.object(torch.cuda, 'get_device_name', return_value='CPU test'), \ | |
| patch.object(torch, 'autocast', side_effect=lambda *a, **k: nullcontext()), \ | |
| redirect_stdout(io.StringIO()): | |
| editing.main() | |
| summary = json.loads((output / 'summary.json').read_text()) | |
| self.assertEqual(summary['count'], count) | |
| with Image.open(output / 'comparison.png') as comparison: | |
| self.assertEqual(comparison.size, (8, 32 + preview_count * 4)) | |
| for row, report in enumerate(summary['images'][:preview_count]): | |
| for column, kind in enumerate(('source', 'editing')): | |
| with Image.open(output / kind / report['category'] / (report['id'] + '.png')) as expected: | |
| crop = comparison.crop((column * 4, 32 + row * 4, | |
| (column + 1) * 4, 32 + (row + 1) * 4)) | |
| self.assertEqual(crop.tobytes(), expected.tobytes()) | |
| def test_training_noise_pipeline_uses_target_denoising_and_preserves_cfg_precision(self): | |
| from PIL import Image | |
| from pie_bench_nf_components import add_training_noise | |
| from utils.inference import self_denoise | |
| class FakeVAE(torch.nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| self.scaling_factor, self.downsample_factor = 0.5, 1 | |
| self.decoded = [] | |
| self.vae = SimpleNamespace(encode=lambda image: SimpleNamespace( | |
| latent_dist=SimpleNamespace(mode=lambda: (image[:, :2] * 0.5).bfloat16()))) | |
| def decode(self, latent): | |
| self.decoded.append(latent.detach().clone()) | |
| return torch.cat([latent, latent[:, :1]], 1) | |
| buffer = io.BytesIO() | |
| Image.new('RGB', (4, 4), (180, 100, 80)).save(buffer, format='PNG') | |
| items = [{'category': category, 'id': image_id, 'image_bytes': buffer.getvalue(), | |
| 'source_prompt': 'source', 'target_prompt': 'target'} | |
| for category, image_id in (('0_random_140', '7'), ('single', 'input.v1'))] | |
| model = self.make_model(patch_size=2).cpu() | |
| conditions = torch.randn(3, 3, 8) | |
| noisy_inputs = {} | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| for cfg, sweep in product((0.0, 3.6), (0, 1)): | |
| with self.subTest(cfg=cfg, sweep=sweep): | |
| args = SimpleNamespace(img_size=4, txt_size=3, cond_noise_level=int(cfg > 0), | |
| noise_type='gaussian', noise_std=0.3) | |
| vae = FakeVAE() | |
| components = (args, model, vae, None, torch.nn.Identity(), | |
| SimpleNamespace(distributed=False), torch.device('cpu')) | |
| denoise = Mock(wraps=self_denoise) | |
| encode = Mock(side_effect=lambda *a, **k: conditions[:len(a[2])]) | |
| mocks = {'pie_bench_nf_components': SimpleNamespace( | |
| load_components=lambda cli: components, add_training_noise=add_training_noise), | |
| 'utils': SimpleNamespace(encode_text=encode, self_denoise=denoise)} | |
| output = root / f'cfg_{cfg}_sweep_{sweep}' | |
| alpha, gamma = (1.0, 0.0) if sweep == 0 else (1.5, 1.0) | |
| argv = ['editing', '--max-samples', '2', '--skip-metrics', '--training-noise', '--cfg', str(cfg), | |
| '--alpha', str(alpha), '--beta', '0', '--gamma', str(gamma), | |
| '--output-dir', str(output)] | |
| selected = items if sweep == 0 else items[::-1] | |
| with patch.dict(sys.modules, mocks), patch.object(sys, 'argv', argv), \ | |
| patch.dict(os.environ, {'WORLD_SIZE': '1'}), \ | |
| patch.object(editing, 'iter_inputs', side_effect=lambda cli: iter(selected)), \ | |
| patch.object(torch.cuda, 'is_available', return_value=True), \ | |
| patch.object(torch.cuda, 'get_device_name', return_value='CPU test'), \ | |
| patch.object(torch, 'autocast', side_effect=lambda *a, **k: nullcontext()), \ | |
| redirect_stdout(io.StringIO()): | |
| editing.main() | |
| self.assertEqual(denoise.call_count, 2) | |
| self.assertFalse(model.training) | |
| self.assertTrue(all(p.grad is None and not p.requires_grad for p in model.parameters())) | |
| config = json.loads((output / 'run_config.json').read_text()) | |
| self.assertTrue(config['training_noise']) | |
| self.assertEqual(config['self_denoising_steps'], 1) | |
| self.assertEqual(config['input_noise_std'], 0.3) | |
| self.assertEqual(config['method_version'], 2) | |
| self.assertEqual(config['affine_precision'], 'fp64' if cfg else 'fp32') | |
| self.assertEqual(json.loads((output / 'summary.json').read_text())['count'], 2) | |
| for index, item in enumerate(selected): | |
| stem = Path(item['category']) / item['id'] | |
| saved = torch.load(output / 'states' / stem.with_name(stem.name + '.pt'), | |
| weights_only=True) | |
| report = json.loads((output / 'metadata' / stem.with_name(stem.name + '.json')).read_text()) | |
| image_seed = int(item['id']) if item['id'].isdigit() else sum(map(ord, item['id'])) | |
| noise_seed = 999 + sum(map(ord, item['category'])) + image_seed + 1_000_003 | |
| self.assertEqual(report['noise_seed'], noise_seed) | |
| self.assertTrue(report['training_noise']) | |
| self.assertEqual(report['self_denoising_steps'], 1) | |
| torch.testing.assert_close(saved['u_source'], add_training_noise( | |
| saved['u_source_clean'], args, noise_seed), atol=0, rtol=0) | |
| key = (item['category'], item['id']) | |
| if key in noisy_inputs: | |
| torch.testing.assert_close(saved['u_source'], noisy_inputs[key], atol=0, rtol=0) | |
| noisy_inputs[key] = saved['u_source'] | |
| call = denoise.call_args_list[index] | |
| self.assertIs(call.args[0], model) | |
| torch.testing.assert_close(call.args[1], saved['u_edit'], atol=0, rtol=0) | |
| torch.testing.assert_close(call.args[2], conditions[1:2], atol=0, rtol=0) | |
| self.assertEqual(call.kwargs, {'noise_std': 0.3, 'lr': 1, 'steps': 1}) | |
| self.assertEqual(encode.call_args_list[index].kwargs['noise_std'], 0.3 if cfg else None) | |
| decode_dtype = torch.bfloat16 if cfg else torch.float32 | |
| self.assertEqual(report['vae_decode_dtype'], str(decode_dtype)) | |
| self.assertEqual(saved['z_source'].dtype, torch.float64 if cfg else torch.float32) | |
| self.assertEqual(saved['u_edit_denoised'].dtype, torch.float32) | |
| self.assertEqual(vae.decoded[2 * index].dtype, decode_dtype) | |
| self.assertEqual(vae.decoded[2 * index + 1].dtype, decode_dtype) | |
| torch.testing.assert_close(vae.decoded[2 * index], | |
| saved['u_source_clean'].to(decode_dtype), atol=0, rtol=0) | |
| torch.testing.assert_close(vae.decoded[2 * index + 1], | |
| saved['u_edit_denoised'].to(decode_dtype), atol=0, rtol=0) | |
| self.assertGreater((saved['u_edit_denoised'] - saved['u_edit']).abs().max().item(), 0) | |
| def test_shell_preserves_current_run_and_forwards_cfg(self): | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| log = root / 'calls.jsonl' | |
| python = root / 'fake_python' | |
| python.write_text(f'#!{sys.executable}\n' + '''import json | |
| import os | |
| import sys | |
| with open(os.environ['SADAE_SWEEP_LOG'], 'a') as stream: | |
| stream.write(json.dumps(sys.argv[1:]) + '\\n') | |
| ''') | |
| python.chmod(0o700) | |
| output = root / 'sweep results' | |
| command = ['bash', str(editing.ROOT / 'scripts/nf_source_anchored_decoupled_affine_editing.sh'), | |
| '--output-dir', str(output), '--category', 'category with spaces', | |
| '--max-samples', '6', '--comparison-samples', '2', '--cfg', '3.6', | |
| '--dataset', str(root / 'PIE_Bench'), '--metrics-device', 'cpu'] | |
| environment = dict(os.environ, PYTHON=str(python), SADAE_SWEEP_LOG=str(log)) | |
| environment.pop('NPROC_PER_NODE', None) | |
| for devices in ('0,1,2,3', '0'): | |
| environment['CUDA_VISIBLE_DEVICES'] = devices | |
| completed = subprocess.run(command, env=environment, capture_output=True, text=True) | |
| self.assertEqual(completed.returncode, 0, completed.stderr) | |
| calls = [json.loads(line) for line in log.read_text().splitlines()] | |
| self.assertEqual(len(calls), 2) | |
| pairs, directories = [], set() | |
| for args, workers in zip(calls, ('4', '1')): | |
| self.assertEqual(args[:4], ['-m', 'torch.distributed.run', '--standalone', '--nnodes=1']) | |
| self.assertEqual(args[args.index('--nproc-per-node') + 1], workers) | |
| alpha, beta = args[args.index('--alpha') + 1], args[args.index('--beta') + 1] | |
| gamma = args[args.index('--gamma') + 1] | |
| pairs.append((alpha, beta)) | |
| directory = args[args.index('--output-dir') + 1] | |
| directories.add(directory) | |
| self.assertEqual(directory, str(output / f'alpha_{alpha}_beta_{beta}_gamma_{gamma}')) | |
| self.assertEqual(args[args.index('--category') + 1], 'category with spaces') | |
| self.assertEqual(args[args.index('--max-samples') + 1], '6') | |
| self.assertEqual(args[args.index('--comparison-samples') + 1], '2') | |
| self.assertEqual(gamma, '1.0') | |
| self.assertIn('--training-noise', args) | |
| self.assertEqual(args[args.index('--cfg') + 1], '3.6') | |
| self.assertEqual(args[args.index('--dataset') + 1], str(root / 'PIE_Bench')) | |
| self.assertEqual(args[args.index('--metrics-device') + 1], 'cpu') | |
| self.assertEqual(pairs, [('1.5', '0.5')] * 2) | |
| self.assertEqual(len(directories), 1) | |
| output.mkdir() | |
| repeated = subprocess.run(command, env=environment, capture_output=True, text=True) | |
| self.assertNotEqual(repeated.returncode, 0) | |
| self.assertEqual(len(log.read_text().splitlines()), 2) | |
| def test_pie_selection_and_prompt_cleanup(self): | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| with tempfile.TemporaryDirectory() as temporary: | |
| category = Path(temporary) / 'category' | |
| category.mkdir() | |
| rows = [{'image': {'bytes': b'png'}, 'id': str(i), | |
| 'source_prompt': ' [source] ', 'target_prompt': 'a [target]', 'mask': '1 2'} for i in (0, 9)] | |
| pq.write_table(pa.Table.from_pylist(rows), category / 'data.parquet') | |
| cli = SimpleNamespace(image_path=None, dataset=Path(temporary), category=['category'], | |
| image_id=[9], start_index=0, skip_metrics=False) | |
| selected = list(editing.iter_inputs(cli)) | |
| self.assertEqual(len(selected), 1) | |
| self.assertEqual(selected[0]['id'], '9') | |
| self.assertEqual(selected[0]['source_prompt'], 'source') | |
| self.assertEqual(selected[0]['target_prompt'], 'a target') | |
| self.assertEqual(selected[0]['pie_mask'], '1 2') | |
| cli.image_id = [8] | |
| with self.assertRaisesRegex(ValueError, 'IDs missing'): | |
| list(editing.iter_inputs(cli)) | |
| def test_original_pie_bench_selection_and_prompt_cleanup(self): | |
| with tempfile.TemporaryDirectory() as temporary: | |
| dataset = Path(temporary) | |
| mapping = {} | |
| for category, image_id in (('0_random_140', '000000000001'), | |
| ('1_change_object_80', '000000000140'), | |
| ('0_random_140', '000000000009')): | |
| relative = f'{category}/{image_id}.jpg' | |
| path = dataset / 'annotation_images' / relative | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_bytes(b'jpeg') | |
| mapping[image_id] = {'image_path': relative, 'original_prompt': ' a [cat] ', | |
| 'editing_prompt': 'a [dog]', 'mask': [1, 2]} | |
| (dataset / 'mapping_file.json').write_text(json.dumps(mapping)) | |
| cli = SimpleNamespace(image_path=None, dataset=dataset, category=None, | |
| image_id=None, start_index=0, skip_metrics=False) | |
| selected = list(editing.iter_inputs(cli)) | |
| self.assertEqual([row['id'] for row in selected], list(mapping)) | |
| self.assertEqual(selected[0]['image_bytes'], b'jpeg') | |
| self.assertEqual(selected[0]['source_prompt'], 'a cat') | |
| self.assertEqual(selected[0]['target_prompt'], 'a dog') | |
| self.assertEqual(selected[0]['pie_mask'], [1, 2]) | |
| cli.category, cli.start_index, cli.image_id = ['0_random_140'], 1, [9] | |
| selected = list(editing.iter_inputs(cli)) | |
| self.assertEqual([row['id'] for row in selected], ['000000000009']) | |
| cli.image_id = [140] | |
| with self.assertRaisesRegex(ValueError, 'IDs missing'): | |
| list(editing.iter_inputs(cli)) | |
| cli.category = ['unknown'] | |
| with self.assertRaisesRegex(ValueError, 'Unknown PIE categories'): | |
| list(editing.iter_inputs(cli)) | |
| def test_original_pie_bench_pipeline_saves_metrics_and_can_skip_evaluation(self): | |
| from PIL import Image | |
| import pie_bench_metrics as metrics | |
| class FakeVAE(torch.nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| self.scaling_factor, self.downsample_factor = 1, 1 | |
| self.vae = SimpleNamespace(encode=lambda image: SimpleNamespace( | |
| latent_dist=SimpleNamespace(mode=lambda: image[:, :2]))) | |
| def decode(self, latent): | |
| return torch.cat([latent, latent[:, :1]], 1) | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| dataset = root / 'dataset' | |
| image_path = dataset / 'annotation_images/0_random_140/000000000009.jpg' | |
| image_path.parent.mkdir(parents=True) | |
| Image.new('RGB', (8, 4), (180, 100, 80)).save(image_path) | |
| (dataset / 'mapping_file.json').write_text(json.dumps({'000000000009': { | |
| 'image_path': '0_random_140/000000000009.jpg', 'original_prompt': 'a [cat]', | |
| 'editing_prompt': 'a [dog]', 'mask': [12, 1], | |
| }})) | |
| model = self.make_model(patch_size=2).cpu() | |
| components = (SimpleNamespace(img_size=4, txt_size=3, cond_noise_level=0), model, | |
| FakeVAE(), None, torch.nn.Identity(), SimpleNamespace(distributed=False), | |
| torch.device('cpu')) | |
| encode = Mock(return_value=torch.randn(2, 3, 8)) | |
| mocks = {'pie_bench_nf_components': SimpleNamespace(load_components=lambda cli: components), | |
| 'utils': SimpleNamespace(encode_text=encode)} | |
| scores = {name: 0.25 for name in metrics.METRIC_NAMES} | |
| for skip in (False, True): | |
| output = root / f'output_skip_{skip}' | |
| calculator = Mock() | |
| calculator.calculate.return_value = scores | |
| argv = ['editing', '--dataset', str(dataset), '--image-id', '9', | |
| '--metrics-device', 'cpu', '--output-dir', str(output)] | |
| if skip: | |
| argv.append('--skip-metrics') | |
| with patch.dict(sys.modules, mocks), patch.object(sys, 'argv', argv), \ | |
| patch.object(torch.cuda, 'is_available', return_value=True), \ | |
| patch.object(torch.cuda, 'get_device_name', return_value='CPU test'), \ | |
| patch.object(torch, 'autocast', side_effect=lambda *a, **k: nullcontext()), \ | |
| patch.object(metrics, 'PieBenchMetrics', return_value=calculator) as create_calculator, \ | |
| redirect_stdout(io.StringIO()): | |
| editing.main() | |
| summary = json.loads((output / 'summary.json').read_text()) | |
| self.assertEqual(summary['count'], 1) | |
| self.assertEqual(encode.call_args.args[2], ['a cat', 'a dog']) | |
| self.assertEqual((output / 'metrics.csv').exists(), not skip) | |
| if skip: | |
| create_calculator.assert_not_called() | |
| self.assertNotIn('pie_bench_metrics', summary) | |
| continue | |
| create_calculator.assert_called_once_with('cpu') | |
| source, edited, mask, prompt = calculator.calculate.call_args.args | |
| self.assertEqual(source.shape, (3, 4, 4)) | |
| self.assertEqual(edited.dtype, torch.uint8) | |
| self.assertEqual(prompt, 'a dog') | |
| torch.testing.assert_close(mask, metrics.preprocess_pie_mask( | |
| [12, 1], image_path.read_bytes(), 4)) | |
| self.assertEqual(summary['images'][0]['pie_bench_metrics'], scores) | |
| for name in metrics.METRIC_NAMES: | |
| self.assertEqual(summary['pie_bench_metrics']['statistics'][name], | |
| {'mean': 0.25, 'std': 0.0, 'count': 1}) | |
| metadata = json.loads((output / 'metadata/0_random_140/000000000009.json').read_text()) | |
| self.assertEqual(metadata['pie_bench_metrics'], scores) | |
| self.assertEqual(metadata['pie_bench_mask_fraction'], mask.float().mean().item()) | |
| if __name__ == '__main__': | |
| unittest.main() | |