Download scripts/test_nf_training_noise.py from Lingmin-Ran/SADAE: direct link, hf CLI and curl.
- Browser
- Download file 6.27 kB
-
https://huggingface.co/Lingmin-Ran/SADAE/resolve/main/scripts/test_nf_training_noise.py
- Command line
-
hf download hf://Lingmin-Ran/SADAE/scripts/test_nf_training_noise.py
-
curl -L -o test_nf_training_noise.py https://huggingface.co/Lingmin-Ran/SADAE/resolve/main/scripts/test_nf_training_noise.py
6.27 kB
| #!/usr/bin/env python3 | |
| """Check reproducible training noise and the NLL/KL input pipelines on CPU.""" | |
| from contextlib import nullcontext, redirect_stdout | |
| import io | |
| import json | |
| from pathlib import Path | |
| import sys | |
| import tempfile | |
| from types import SimpleNamespace | |
| import unittest | |
| from unittest.mock import patch | |
| import torch | |
| from PIL import Image | |
| from pie_bench_nf_components import add_training_noise | |
| from transformer_flow import Model | |
| import visualize_pie_bench_token_kl as kl_script | |
| import visualize_pie_bench_token_nll_delta as nll_script | |
| class TrainingNoiseTests(unittest.TestCase): | |
| def setUpClass(cls): | |
| torch.set_num_threads(1) | |
| def test_noise_reproducible_without_changing_global_rng(self): | |
| args = SimpleNamespace(noise_type='gaussian', noise_std=0.3) | |
| latent = torch.zeros(1, 4, 128, 128) | |
| before = torch.random.get_rng_state() | |
| noisy = add_training_noise(latent, args, 2027) | |
| torch.testing.assert_close(torch.random.get_rng_state(), before, atol=0, rtol=0) | |
| torch.randn(17) | |
| torch.testing.assert_close(add_training_noise(latent, args, 2027), noisy, atol=0, rtol=0) | |
| self.assertFalse(torch.equal(add_training_noise(latent, args, 2028), noisy)) | |
| self.assertAlmostEqual(noisy.std().item(), 0.3, delta=0.003) | |
| self.assertAlmostEqual(noisy.mean().item(), 0, delta=0.004) | |
| self.assertEqual(latent.count_nonzero(), 0) | |
| with self.assertRaises(ValueError): | |
| add_training_noise(latent, SimpleNamespace(noise_type='uniform', noise_std=0.3), 2027) | |
| def test_visualizers_score_the_same_seeded_noisy_latent(self): | |
| torch.manual_seed(8) | |
| model = Model(in_channels=2, img_size=4, patch_size=1, channels=32, num_blocks=2, | |
| layers_per_block=[1, 1], head_dim=32, rope=True, sos=True, | |
| txt_size=3, txt_dim=8, cond_top_only=True, use_softplus=True).eval() | |
| with torch.no_grad(): | |
| for block in model.blocks: | |
| block.proj_out.weight.normal_(std=0.04) | |
| model.requires_grad_(False) | |
| cs, ct = torch.randn(1, 3, 8), torch.randn(1, 3, 8) | |
| args = SimpleNamespace(img_size=4, txt_size=3, cond_noise_level=0, | |
| noise_type='gaussian', noise_std=0.3) | |
| image_buffer = io.BytesIO() | |
| Image.new('RGB', (4, 4), (180, 100, 80)).save(image_buffer, format='PNG') | |
| row = {'id': '000000000007', 'source_prompt': 'source', 'target_prompt': 'target', | |
| 'image': {'bytes': image_buffer.getvalue()}} | |
| parquet = SimpleNamespace(iter_batches=lambda **kwargs: [SimpleNamespace(to_pylist=lambda: [row])]) | |
| vae = SimpleNamespace(scaling_factor=1, downsample_factor=1, | |
| vae=SimpleNamespace(encode=lambda image: SimpleNamespace( | |
| latent_dist=SimpleNamespace(mode=lambda: image[:, :2] * 0.5)))) | |
| components = (args, model, vae, None, None, None, torch.device('cpu')) | |
| mocks = {'pie_bench_nf_components': SimpleNamespace(load_components=lambda cli: components, | |
| add_training_noise=add_training_noise), | |
| 'utils': SimpleNamespace(encode_text=lambda _, __, prompts, *a, **k: | |
| cs if prompts == ['source'] else ct)} | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| category = root / '0_random_140' | |
| category.mkdir() | |
| (category / 'part.parquet').touch() | |
| noisy_queries = [] | |
| for module, function_name in ((nll_script, 'token_nll'), (kl_script, 'conditional_kl_maps')): | |
| for training_noise in (False, True): | |
| with self.subTest(script=module.__name__, training_noise=training_noise): | |
| output = root / f'{module.__name__}_{training_noise}' | |
| argv = [module.__name__, '--dataset', str(root), '--category', category.name, | |
| '--image-id', '7', '--output-dir', str(output)] | |
| if training_noise: | |
| argv.append('--training-noise') | |
| original = getattr(module, function_name) | |
| queries = [] | |
| def capture(model, latent, *conditions): | |
| queries.append(latent.clone()) | |
| return original(model, latent, *conditions) | |
| with patch.dict(sys.modules, mocks), patch.object(sys, 'argv', argv), \ | |
| patch.object(module.pq, 'ParquetFile', return_value=parquet), \ | |
| patch.object(torch.cuda, 'is_available', return_value=True), \ | |
| patch.object(torch, 'autocast', side_effect=lambda *a, **k: nullcontext()), \ | |
| patch.object(module, function_name, side_effect=capture), \ | |
| redirect_stdout(io.StringIO()): | |
| module.main() | |
| summary = json.loads((output / 'summary.json').read_text()) | |
| clean = torch.tensor([180 / 127.5 - 1, 100 / 127.5 - 1]).view(1, 2, 1, 1) | |
| clean = clean.expand(1, 2, 4, 4) * 0.5 | |
| expected_seed = 999 + sum(ord(c) for c in category.name) + 7 + 1_000_003 | |
| expected = add_training_noise(clean, args, expected_seed) if training_noise else clean | |
| torch.testing.assert_close(queries[0], expected, atol=1e-7, rtol=1e-7) | |
| for query in queries[1:]: | |
| torch.testing.assert_close(query, queries[0], atol=0, rtol=0) | |
| self.assertEqual(summary['input_noise_std'], 0.3 if training_noise else 0.0) | |
| self.assertEqual(summary['noise_seed'], expected_seed if training_noise else None) | |
| if training_noise: | |
| noisy_queries.append(queries[0]) | |
| torch.testing.assert_close(noisy_queries[0], noisy_queries[1], atol=0, rtol=0) | |
| if __name__ == '__main__': | |
| unittest.main() | |