devilops commited on
Commit
38e9b9a
·
1 Parent(s): 408200e

initial commit

Browse files
Files changed (36) hide show
  1. LICENSE +21 -0
  2. __init__.py +0 -0
  3. __pycache__/__init__.cpython-39.pyc +0 -0
  4. configs/__init__.py +90 -0
  5. configs/default.yml +70 -0
  6. configs/imagenet1000.yml +196 -0
  7. diffusion_ckpts/256x256_diffusion_uncond.pt +3 -0
  8. guided_diffusion/.gitignore +3 -0
  9. guided_diffusion/LICENSE +21 -0
  10. guided_diffusion/README.md +176 -0
  11. guided_diffusion/__init__.py +0 -0
  12. guided_diffusion/dist_util.py +93 -0
  13. guided_diffusion/guided_diffusion/__init__.py +3 -0
  14. guided_diffusion/guided_diffusion/dist_util.py +93 -0
  15. guided_diffusion/guided_diffusion/fp16_util.py +236 -0
  16. guided_diffusion/guided_diffusion/gaussian_diffusion.py +1252 -0
  17. guided_diffusion/guided_diffusion/image_datasets.py +167 -0
  18. guided_diffusion/guided_diffusion/logger.py +495 -0
  19. guided_diffusion/guided_diffusion/losses.py +77 -0
  20. guided_diffusion/guided_diffusion/nn.py +170 -0
  21. guided_diffusion/guided_diffusion/resample.py +154 -0
  22. guided_diffusion/guided_diffusion/respace.py +128 -0
  23. guided_diffusion/guided_diffusion/script_util.py +452 -0
  24. guided_diffusion/guided_diffusion/train_util.py +301 -0
  25. guided_diffusion/guided_diffusion/unet.py +908 -0
  26. guided_diffusion/model-card.md +59 -0
  27. guided_diffusion/scripts/classifier_sample.py +131 -0
  28. guided_diffusion/scripts/classifier_train.py +226 -0
  29. guided_diffusion/scripts/image_nll.py +96 -0
  30. guided_diffusion/scripts/image_sample.py +108 -0
  31. guided_diffusion/scripts/image_train.py +83 -0
  32. guided_diffusion/scripts/super_res_sample.py +119 -0
  33. guided_diffusion/scripts/super_res_train.py +98 -0
  34. guided_diffusion/setup.py +7 -0
  35. main.py +9 -0
  36. resizer.py +198 -0
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Omri Avrahami
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
__init__.py ADDED
File without changes
__pycache__/__init__.cpython-39.pyc ADDED
Binary file (175 Bytes). View file
 
configs/__init__.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import yaml
5
+
6
+ __all__ = ['get_config', 'print_config']
7
+
8
+
9
+ def get_config(args):
10
+
11
+ config = dict2namespace(setdefault(_get_raw_config(args.config), _get_raw_config("default.yml")))
12
+
13
+ if not hasattr(config.sampling, "sigma_dist"):
14
+ config.sampling.sigma_dist = config.model.sigma_dist
15
+ if not hasattr(config.biggan, "resolution"):
16
+ config.biggan.resolution = config.data.image_size
17
+
18
+ if args.consistent:
19
+ config.sampling.consistent = args.consistent
20
+ config.sampling.noise_first = False
21
+ if args.step_lr:
22
+ config.sampling.step_lr = args.step_lr
23
+ if args.nsigma != 0:
24
+ config.sampling.nsigma = args.nsigma
25
+ if args.step_lr != 0:
26
+ config.sampling.step_lr = args.step_lr
27
+ if args.batch_size != 0:
28
+ config.sampling.batch_size = args.batch_size
29
+ config.fast_fid.batch_size = args.batch_size
30
+ # ToDo: experimental and is only using model_types
31
+ if args.model_types is not None and len(args.model_types)==1 and args.model_types[0] in [0, 6, 23] and config.data.dataset in ['tinyImages', 'CIFAR10']:
32
+ config.sampling.batch_size = min(200, config.sampling.batch_size)
33
+ if args.model_types is not None and len(args.model_types) == 1 and args.model_types[0] in [8] and config.data.dataset in ['tinyImages', 'CIFAR10']:
34
+ config.sampling.batch_size = min(800, config.sampling.batch_size)
35
+
36
+ if args.ODI_steps == -1:
37
+ args.ODI_steps = None
38
+ if args.fid_num_samples != 0:
39
+ config.fast_fid.num_samples = args.fid_num_samples
40
+ if args.begin_ckpt != 0:
41
+ config.fast_fid.begin_ckpt = args.begin_ckpt
42
+ config.sampling.ckpt_id = args.begin_ckpt
43
+ if args.end_ckpt != 0:
44
+ config.fast_fid.end_ckpt = args.begin_ckpt
45
+ if args.adam:
46
+ config.optim.beta1 = args.adam_beta[0]
47
+ config.optim.beta2 = args.adam_beta[1]
48
+ if args.D_adam:
49
+ config.optim.adv_beta1 = args.D_adam_beta[0]
50
+ config.optim.adv_beta2 = args.D_adam_beta[1]
51
+ if args.D_steps != 0:
52
+ config.adversarial.D_steps = args.D_steps
53
+
54
+ return config
55
+
56
+
57
+ def _get_raw_config(name):
58
+ here = os.path.dirname(os.path.abspath(__file__))
59
+ with open(os.path.join(here, name), 'r') as f:
60
+ yaml_dict = yaml.load(f, Loader=yaml.FullLoader)
61
+ return yaml_dict
62
+
63
+
64
+ def setdefault(config, default):
65
+ #print('config is', config, 'default is', default)
66
+ for x in default:
67
+ v = default.get(x)
68
+ if isinstance(v, dict) and x in config:
69
+ setdefault(config.get(x), v)
70
+ else:
71
+ config.setdefault(x, v)
72
+ return config
73
+
74
+
75
+ def dict2namespace(config):
76
+ namespace = argparse.Namespace()
77
+ for key, value in config.items():
78
+ if isinstance(value, dict):
79
+ new_value = dict2namespace(value)
80
+ else:
81
+ new_value = value
82
+ setattr(namespace, key, new_value)
83
+ return namespace
84
+
85
+
86
+ def print_config(config):
87
+ print(">" * 80)
88
+ print(yaml.dump(config, default_flow_style=False))
89
+ print("<" * 80)
90
+
configs/default.yml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data:
2
+ dataset: LSUN
3
+ category: church_outdoor
4
+ image_size: 64
5
+ channels: 3
6
+ logit_transform: false
7
+ uniform_dequantization: false
8
+ gaussian_dequantization: false
9
+ random_flip: true
10
+ rescaled: false
11
+ num_workers: 32
12
+
13
+ model:
14
+ sigma_begin: 140
15
+ num_classes: 788
16
+ ema: true
17
+ ema_rate: 0.999
18
+ spec_norm: false
19
+ sigma_dist: geometric
20
+ sigma_end: 0.01
21
+ normalization: InstanceNorm++
22
+ nonlinearity: elu
23
+ ngf: 128
24
+ unet: false
25
+ dropout: 0.0
26
+
27
+ sampling:
28
+ noise_first: false
29
+ clamp: false
30
+ experiment_name: 'logits_evolution_tracking_best_point'
31
+
32
+ training:
33
+ log_all_sigmas: true # whether to send training information to tensorboard
34
+
35
+ optim:
36
+ weight_decay: 0.000
37
+ optimizer: Adam
38
+ lr: 0.0001
39
+ beta1: 0.9
40
+ beta2: 0.999
41
+ adv_beta1: -0.5
42
+ adv_beta2: 0.9
43
+ amsgrad: false
44
+ eps: 0.00000001
45
+ momentum: 0.9
46
+
47
+ fast_fid:
48
+ batch_size: 50
49
+ num_samples: 1000
50
+
51
+ adversarial:
52
+ lambda_dae: 1 # multiplier term for Lp loss function (only used in GAN setting)
53
+ lambda_D: 1 # multiplier term for GAN loss of the discriminator'
54
+ lambda_G_gan: 1 # multiplier term for GAN loss of the generator
55
+ D_steps: 1 # Discriminator steps per Generator step
56
+ adv_loss: LSGAN # 'GAN, LSGAN, HingeGAN, RpGAN, RaGAN, RaLSGAN, RaHingeGAN'
57
+ arch: 2 # 0 is DCGAN_D0, 1 is DCGAN_D1, 2 is BigGAN
58
+ spectral: false # If True, spectral normalization in D
59
+ no_batch_norm_D: false # Not active in BigGAN
60
+ adv_clamp: true # If True, do not clamp output of score network before giving to discriminator
61
+
62
+ biggan:
63
+ ch: 64 # Number of channels
64
+ thin: false # If True, use thin Discriminator (D_ch = 0 with D_thin = True leads to )
65
+ kernel_size: 3
66
+ attn: '64' # Number of attention filters (If 0, do not use self-attention)
67
+ n_classes: 1 # Number of classes of the dataset (If = 1 leads to Unconditional GAN) # inactive
68
+ init: xavier # Type of init,: ortho, xavier, N02
69
+
70
+
configs/imagenet1000.yml ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ training:
2
+ batch_size: 128
3
+ n_epochs: 500000
4
+ n_iters: 300001
5
+ snapshot_freq: 5000
6
+ snapshot_sampling: false
7
+ snapshot_sampling_freq: 5000
8
+ anneal_power: 2
9
+ log_all_sigmas: false
10
+
11
+ sampling:
12
+ batch_size: 100 # 25 for randomized smoothing, 100 otherwise
13
+ data_init: false # true for CLIP
14
+ data_init_correct_class: false
15
+ random_label_data_init: false # true for CLIP
16
+ model_failure_examples_init: true # false for CLIP
17
+ model_failure_examples_init_wrong_class: false
18
+ name_init: false
19
+ init_data_seed: 1234 # set it to the same seed (1234)! 1239 for CLIP
20
+ step_lr: 0.0000062
21
+ nsigma: 5
22
+ ckpt_id: 260000
23
+ final_only: false
24
+ fid: false
25
+ num_samples4fid: 10000
26
+ inpainting: false
27
+ interpolation: false
28
+ n_interpolations: 15
29
+ noise_first: true
30
+ save_freq: 1
31
+ consistent: false
32
+ conditional: true
33
+ model_description:
34
+ type: ['benchmark-Madry_l2_experimental'] # benchmark-Madry_l2_improved, benchmark-Madry_linf_improved,
35
+ # benchmark-Madry_l2_experimental, benchmark-Madry_linf_experimental
36
+ # benchmark-Madry_l2_improved_eps_1
37
+
38
+ folder: 'AdvACET_24-02-2020_14:41:39'
39
+ checkpoint: 'final'
40
+ temperature: null # 0.41
41
+ load_temp: false
42
+ line_search:
43
+ type: 'armijo' # 'wolfe_conditions' # 'armijo' # 'wolfe_conditions' # wolfe_conditions, armijo_momentum_prox, armijo
44
+ beta_1: 0.0001
45
+ beta_2: 0.9999
46
+ alpha_lower_bound: 0.0001
47
+ alpha_current: 100.0 # 1000, change it to 100
48
+ inverse_mode:
49
+ noise: 'gaussian'
50
+ init_apgd_eps: 3.9
51
+ init_apgd_steps: 5
52
+ n_restarts: 5
53
+ activate: false
54
+ type: 'not_dynamic_penalty' # alma, not_dynamic_penalty
55
+ multiplier: 10000 # 1000, 10 not used in current, augmented Lagrangian setting - ToDo - delete?
56
+ inverse_mode_threshold_probs: 0.99974
57
+ norm: 'l2' # l2, l1, LPIPS, 1.5, FeatureDist
58
+ # further hyper-parameters according to https://github.com/jeromerony/adversarial-library/blob/main/adv_lib/attacks/augmented_lagrangian_attacks/alma.py
59
+ penalty_multiplier_init: 1
60
+ lagrange_multiplier_init: 1
61
+ lr_init: 0.1 # 0.1
62
+ is_adv: null
63
+ penalty_multiplier: null
64
+ lagrange_multiplier: null
65
+ lr_reduction: 0.1
66
+ constr_improvement_rate: 0.95
67
+ prev_constraint: null
68
+ ema_weight: 0.999
69
+ penalty_param_increase: 10 #1.2
70
+ check_steps: 10
71
+ init_lr_distance: null # 0.1
72
+ # RMSProp-related constants
73
+ square_avg: null
74
+ # ToDo: what is a better initial value for RMSProp? 0 vs 1?
75
+ square_avg_init: 0 # 1
76
+ alpha: 0.99
77
+ eps: 1e-9 # 1e-8
78
+ # Adam-related constants
79
+ beta_1: 0.9
80
+ beta_2: 0.999
81
+ ratio_mode:
82
+ no_apgd: false
83
+ frank_wolfe:
84
+ decay: false
85
+ activate: false
86
+ constraint: 'intersection'
87
+ momentum: 0 # 0.9
88
+ backtracking_LS:
89
+ activate: false
90
+ L: null
91
+ eta: 0.9 # 0.9
92
+ tau: 2 # 2
93
+ gamma_max: 1
94
+ eps: 0.001
95
+ randomized_smoothing: False
96
+ randomized_smoothing_sigma: 0.25 # 0.25
97
+ activate: false
98
+ noise: false # gaussian, uniform, false
99
+ loss_diverse_iter: false # false, 20
100
+ eps_repeat_steps: 2 # 8
101
+ step_lr: 0.5 # 0.1
102
+ adaptive_stepsize: false
103
+ momentum: false
104
+ grad_normalization: 'l2' # false, l1, l2, l_inf
105
+ apgd:
106
+ pgd_mode: false
107
+ activate: true
108
+ n_restarts: 5
109
+ p_current: 0
110
+ p_next: 0.22
111
+ lr_current: 0.5 # 0.5, 0.9, 10
112
+ lr_next: 0.5 # 0.5, 0.9, 10
113
+ lr_next_for_plotting: 0.5 # 0.5, 0.9, 10
114
+ period_length_red: 0.03
115
+ min_length: 0.06
116
+ loss_values: [ ]
117
+ f_max_current: 0
118
+ f_max_next: 0
119
+ rho: 0.75
120
+ alpha: 0.75
121
+ use_generative_model: false
122
+ grad_scale: 10000
123
+ logits_max: false
124
+ use_noise: false
125
+ project: true
126
+ eps_projection: 1 # for generating misalignment for score networks, when misalignment == true
127
+ eps_begin: 12 # 25 for CLIP
128
+ eps_end: 12 # 25 for CLIP
129
+ experiment_name: 'logits_evolution' #'logits_evolution_FID_imagenet1000'
130
+ save_final_name: false # 'final-most_probable_ood_init_RATIO_232steps' #
131
+ start_with_final_name: false # 'final-most_probable_ood_init_RATIO_232steps', 'final_ood_init_RATIO_232steps'
132
+ norm_projection: 'l2' # 'LPIPS', 'l1', 'l2'
133
+ regularizer: false # false, 'LPIPS', 'l1', 'l2'
134
+ misalignment: false
135
+ calculade_FID_stats: false # true except for FID calculation set to true
136
+ calculade_FID_continue: false
137
+ calculate_FID_continue_path: ''
138
+
139
+ fast_fid:
140
+ batch_size: 1000
141
+ num_samples: 1000
142
+ begin_ckpt: 5000
143
+ end_ckpt: 300000
144
+
145
+ data:
146
+ dataset: "ImageNet1000" # oa-imagenet, CIFAR10
147
+ dataset_for_scorenet: 'ImageNet1000'
148
+ class_labels: ['tench, Tinca tinca', 'goldfish, Carassius auratus', 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias', 'tiger shark, Galeocerdo cuvieri', 'hammerhead, hammerhead shark', 'electric ray, crampfish, numbfish, torpedo', 'stingray', 'cock', 'hen', 'ostrich, Struthio camelus', 'brambling, Fringilla montifringilla', 'goldfinch, Carduelis carduelis', 'house finch, linnet, Carpodacus mexicanus', 'junco, snowbird', 'indigo bunting, indigo finch, indigo bird, Passerina cyanea', 'robin, American robin, Turdus migratorius', 'bulbul', 'jay', 'magpie', 'chickadee', 'water ouzel, dipper', 'kite', 'bald eagle, American eagle, Haliaeetus leucocephalus', 'vulture', 'great grey owl, great gray owl, Strix nebulosa', 'European fire salamander, Salamandra salamandra', 'common newt, Triturus vulgaris', 'eft', 'spotted salamander, Ambystoma maculatum', 'axolotl, mud puppy, Ambystoma mexicanum', 'bullfrog, Rana catesbeiana', 'tree frog, tree-frog', 'tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui', 'loggerhead, loggerhead turtle, Caretta caretta', 'leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea', 'mud turtle', 'terrapin', 'box turtle, box tortoise', 'banded gecko', 'common iguana, iguana, Iguana iguana', 'American chameleon, anole, Anolis carolinensis', 'whiptail, whiptail lizard', 'agama', 'frilled lizard, Chlamydosaurus kingi', 'alligator lizard', 'Gila monster, Heloderma suspectum', 'green lizard, Lacerta viridis', 'African chameleon, Chamaeleo chamaeleon', 'Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis', 'African crocodile, Nile crocodile, Crocodylus niloticus', 'American alligator, Alligator mississipiensis', 'triceratops', 'thunder snake, worm snake, Carphophis amoenus', 'ringneck snake, ring-necked snake, ring snake', 'hognose snake, puff adder, sand viper', 'green snake, grass snake', 'king snake, kingsnake', 'garter snake, grass snake', 'water snake', 'vine snake', 'night snake, Hypsiglena torquata', 'boa constrictor, Constrictor constrictor', 'rock python, rock snake, Python sebae', 'Indian cobra, Naja naja', 'green mamba', 'sea snake', 'horned viper, cerastes, sand viper, horned asp, Cerastes cornutus', 'diamondback, diamondback rattlesnake, Crotalus adamanteus', 'sidewinder, horned rattlesnake, Crotalus cerastes', 'trilobite', 'harvestman, daddy longlegs, Phalangium opilio', 'scorpion', 'black and gold garden spider, Argiope aurantia', 'barn spider, Araneus cavaticus', 'garden spider, Aranea diademata', 'black widow, Latrodectus mactans', 'tarantula', 'wolf spider, hunting spider', 'tick', 'centipede', 'black grouse', 'ptarmigan', 'ruffed grouse, partridge, Bonasa umbellus', 'prairie chicken, prairie grouse, prairie fowl', 'peacock', 'quail', 'partridge', 'African grey, African gray, Psittacus erithacus', 'macaw', 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita', 'lorikeet', 'coucal', 'bee eater', 'hornbill', 'hummingbird', 'jacamar', 'toucan', 'drake', 'red-breasted merganser, Mergus serrator', 'goose', 'black swan, Cygnus atratus', 'tusker', 'echidna, spiny anteater, anteater', 'platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus', 'wallaby, brush kangaroo', 'koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus', 'wombat', 'jellyfish', 'sea anemone, anemone', 'brain coral', 'flatworm, platyhelminth', 'nematode, nematode worm, roundworm', 'conch', 'snail', 'slug', 'sea slug, nudibranch', 'chiton, coat-of-mail shell, sea cradle, polyplacophore', 'chambered nautilus, pearly nautilus, nautilus', 'Dungeness crab, Cancer magister', 'rock crab, Cancer irroratus', 'fiddler crab', 'king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica', 'American lobster, Northern lobster, Maine lobster, Homarus americanus', 'spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish', 'crayfish, crawfish, crawdad, crawdaddy', 'hermit crab', 'isopod', 'white stork, Ciconia ciconia', 'black stork, Ciconia nigra', 'spoonbill', 'flamingo', 'little blue heron, Egretta caerulea', 'American egret, great white heron, Egretta albus', 'bittern', 'crane', 'limpkin, Aramus pictus', 'European gallinule, Porphyrio porphyrio', 'American coot, marsh hen, mud hen, water hen, Fulica americana', 'bustard', 'ruddy turnstone, Arenaria interpres', 'red-backed sandpiper, dunlin, Erolia alpina', 'redshank, Tringa totanus', 'dowitcher', 'oystercatcher, oyster catcher', 'pelican', 'king penguin, Aptenodytes patagonica', 'albatross, mollymawk', 'grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus', 'killer whale, killer, orca, grampus, sea wolf, Orcinus orca', 'dugong, Dugong dugon', 'sea lion', 'Chihuahua', 'Japanese spaniel', 'Maltese dog, Maltese terrier, Maltese', 'Pekinese, Pekingese, Peke', 'Shih-Tzu', 'Blenheim spaniel', 'papillon', 'toy terrier', 'Rhodesian ridgeback', 'Afghan hound, Afghan', 'basset, basset hound', 'beagle', 'bloodhound, sleuthhound', 'bluetick', 'black-and-tan coonhound', 'Walker hound, Walker foxhound', 'English foxhound', 'redbone', 'borzoi, Russian wolfhound', 'Irish wolfhound', 'Italian greyhound', 'whippet', 'Ibizan hound, Ibizan Podenco', 'Norwegian elkhound, elkhound', 'otterhound, otter hound', 'Saluki, gazelle hound', 'Scottish deerhound, deerhound', 'Weimaraner', 'Staffordshire bullterrier, Staffordshire bull terrier', 'American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier', 'Bedlington terrier', 'Border terrier', 'Kerry blue terrier', 'Irish terrier', 'Norfolk terrier', 'Norwich terrier', 'Yorkshire terrier', 'wire-haired fox terrier', 'Lakeland terrier', 'Sealyham terrier, Sealyham', 'Airedale, Airedale terrier', 'cairn, cairn terrier', 'Australian terrier', 'Dandie Dinmont, Dandie Dinmont terrier', 'Boston bull, Boston terrier', 'miniature schnauzer', 'giant schnauzer', 'standard schnauzer', 'Scotch terrier, Scottish terrier, Scottie', 'Tibetan terrier, chrysanthemum dog', 'silky terrier, Sydney silky', 'soft-coated wheaten terrier', 'West Highland white terrier', 'Lhasa, Lhasa apso', 'flat-coated retriever', 'curly-coated retriever', 'golden retriever', 'Labrador retriever', 'Chesapeake Bay retriever', 'German short-haired pointer', 'vizsla, Hungarian pointer', 'English setter', 'Irish setter, red setter', 'Gordon setter', 'Brittany spaniel', 'clumber, clumber spaniel', 'English springer, English springer spaniel', 'Welsh springer spaniel', 'cocker spaniel, English cocker spaniel, cocker', 'Sussex spaniel', 'Irish water spaniel', 'kuvasz', 'schipperke', 'groenendael', 'malinois', 'briard', 'kelpie', 'komondor', 'Old English sheepdog, bobtail', 'Shetland sheepdog, Shetland sheep dog, Shetland', 'collie', 'Border collie', 'Bouvier des Flandres, Bouviers des Flandres', 'Rottweiler', 'German shepherd, German shepherd dog, German police dog, alsatian', 'Doberman, Doberman pinscher', 'miniature pinscher', 'Greater Swiss Mountain dog', 'Bernese mountain dog', 'Appenzeller', 'EntleBucher', 'boxer', 'bull mastiff', 'Tibetan mastiff', 'French bulldog', 'Great Dane', 'Saint Bernard, St Bernard', 'Eskimo dog, husky', 'malamute, malemute, Alaskan malamute', 'Siberian husky', 'dalmatian, coach dog, carriage dog', 'affenpinscher, monkey pinscher, monkey dog', 'basenji', 'pug, pug-dog', 'Leonberg', 'Newfoundland, Newfoundland dog', 'Great Pyrenees', 'Samoyed, Samoyede', 'Pomeranian', 'chow, chow chow', 'keeshond', 'Brabancon griffon', 'Pembroke, Pembroke Welsh corgi', 'Cardigan, Cardigan Welsh corgi', 'toy poodle', 'miniature poodle', 'standard poodle', 'Mexican hairless', 'timber wolf, grey wolf, gray wolf, Canis lupus', 'white wolf, Arctic wolf, Canis lupus tundrarum', 'red wolf, maned wolf, Canis rufus, Canis niger', 'coyote, prairie wolf, brush wolf, Canis latrans', 'dingo, warrigal, warragal, Canis dingo', 'dhole, Cuon alpinus', 'African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus', 'hyena, hyaena', 'red fox, Vulpes vulpes', 'kit fox, Vulpes macrotis', 'Arctic fox, white fox, Alopex lagopus', 'grey fox, gray fox, Urocyon cinereoargenteus', 'tabby, tabby cat', 'tiger cat', 'Persian cat', 'Siamese cat, Siamese', 'Egyptian cat', 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor', 'lynx, catamount', 'leopard, Panthera pardus', 'snow leopard, ounce, Panthera uncia', 'jaguar, panther, Panthera onca, Felis onca', 'lion, king of beasts, Panthera leo', 'tiger, Panthera tigris', 'cheetah, chetah, Acinonyx jubatus', 'brown bear, bruin, Ursus arctos', 'American black bear, black bear, Ursus americanus, Euarctos americanus', 'ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus', 'sloth bear, Melursus ursinus, Ursus ursinus', 'mongoose', 'meerkat, mierkat', 'tiger beetle', 'ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle', 'ground beetle, carabid beetle', 'long-horned beetle, longicorn, longicorn beetle', 'leaf beetle, chrysomelid', 'dung beetle', 'rhinoceros beetle', 'weevil', 'fly', 'bee', 'ant, emmet, pismire', 'grasshopper, hopper', 'cricket', 'walking stick, walkingstick, stick insect', 'cockroach, roach', 'mantis, mantid', 'cicada, cicala', 'leafhopper', 'lacewing, lacewing fly', "dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk", 'damselfly', 'admiral', 'ringlet, ringlet butterfly', 'monarch, monarch butterfly, milkweed butterfly, Danaus plexippus', 'cabbage butterfly', 'sulphur butterfly, sulfur butterfly', 'lycaenid, lycaenid butterfly', 'starfish, sea star', 'sea urchin', 'sea cucumber, holothurian', 'wood rabbit, cottontail, cottontail rabbit', 'hare', 'Angora, Angora rabbit', 'hamster', 'porcupine, hedgehog', 'fox squirrel, eastern fox squirrel, Sciurus niger', 'marmot', 'beaver', 'guinea pig, Cavia cobaya', 'sorrel', 'zebra', 'hog, pig, grunter, squealer, Sus scrofa', 'wild boar, boar, Sus scrofa', 'warthog', 'hippopotamus, hippo, river horse, Hippopotamus amphibius', 'ox', 'water buffalo, water ox, Asiatic buffalo, Bubalus bubalis', 'bison', 'ram, tup', 'bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis', 'ibex, Capra ibex', 'hartebeest', 'impala, Aepyceros melampus', 'gazelle', 'Arabian camel, dromedary, Camelus dromedarius', 'llama', 'weasel', 'mink', 'polecat, fitch, foulmart, foumart, Mustela putorius', 'black-footed ferret, ferret, Mustela nigripes', 'otter', 'skunk, polecat, wood pussy', 'badger', 'armadillo', 'three-toed sloth, ai, Bradypus tridactylus', 'orangutan, orang, orangutang, Pongo pygmaeus', 'gorilla, Gorilla gorilla', 'chimpanzee, chimp, Pan troglodytes', 'gibbon, Hylobates lar', 'siamang, Hylobates syndactylus, Symphalangus syndactylus', 'guenon, guenon monkey', 'patas, hussar monkey, Erythrocebus patas', 'baboon', 'macaque', 'langur', 'colobus, colobus monkey', 'proboscis monkey, Nasalis larvatus', 'marmoset', 'capuchin, ringtail, Cebus capucinus', 'howler monkey, howler', 'titi, titi monkey', 'spider monkey, Ateles geoffroyi', 'squirrel monkey, Saimiri sciureus', 'Madagascar cat, ring-tailed lemur, Lemur catta', 'indri, indris, Indri indri, Indri brevicaudatus', 'Indian elephant, Elephas maximus', 'African elephant, Loxodonta africana', 'lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens', 'giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca', 'barracouta, snoek', 'eel', 'coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch', 'rock beauty, Holocanthus tricolor', 'anemone fish', 'sturgeon', 'gar, garfish, garpike, billfish, Lepisosteus osseus', 'lionfish', 'puffer, pufferfish, blowfish, globefish', 'abacus', 'abaya', "academic gown, academic robe, judge's robe", 'accordion, piano accordion, squeeze box', 'acoustic guitar', 'aircraft carrier, carrier, flattop, attack aircraft carrier', 'airliner', 'airship, dirigible', 'altar', 'ambulance', 'amphibian, amphibious vehicle', 'analog clock', 'apiary, bee house', 'apron', 'ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin', 'assault rifle, assault gun', 'backpack, back pack, knapsack, packsack, rucksack, haversack', 'bakery, bakeshop, bakehouse', 'balance beam, beam', 'balloon', 'ballpoint, ballpoint pen, ballpen, Biro', 'Band Aid', 'banjo', 'bannister, banister, balustrade, balusters, handrail', 'barbell', 'barber chair', 'barbershop', 'barn', 'barometer', 'barrel, cask', 'barrow, garden cart, lawn cart, wheelbarrow', 'baseball', 'basketball', 'bassinet', 'bassoon', 'bathing cap, swimming cap', 'bath towel', 'bathtub, bathing tub, bath, tub', 'beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon', 'beacon, lighthouse, beacon light, pharos', 'beaker', 'bearskin, busby, shako', 'beer bottle', 'beer glass', 'bell cote, bell cot', 'bib', 'bicycle-built-for-two, tandem bicycle, tandem', 'bikini, two-piece', 'binder, ring-binder', 'binoculars, field glasses, opera glasses', 'birdhouse', 'boathouse', 'bobsled, bobsleigh, bob', 'bolo tie, bolo, bola tie, bola', 'bonnet, poke bonnet', 'bookcase', 'bookshop, bookstore, bookstall', 'bottlecap', 'bow', 'bow tie, bow-tie, bowtie', 'brass, memorial tablet, plaque', 'brassiere, bra, bandeau', 'breakwater, groin, groyne, mole, bulwark, seawall, jetty', 'breastplate, aegis, egis', 'broom', 'bucket, pail', 'buckle', 'bulletproof vest', 'bullet train, bullet', 'butcher shop, meat market', 'cab, hack, taxi, taxicab', 'caldron, cauldron', 'candle, taper, wax light', 'cannon', 'canoe', 'can opener, tin opener', 'cardigan', 'car mirror', 'carousel, carrousel, merry-go-round, roundabout, whirligig', "carpenter's kit, tool kit", 'carton', 'car wheel', 'cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM', 'cassette', 'cassette player', 'castle', 'catamaran', 'CD player', 'cello, violoncello', 'cellular telephone, cellular phone, cellphone, cell, mobile phone', 'chain', 'chainlink fence', 'chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour', 'chain saw, chainsaw', 'chest', 'chiffonier, commode', 'chime, bell, gong', 'china cabinet, china closet', 'Christmas stocking', 'church, church building', 'cinema, movie theater, movie theatre, movie house, picture palace', 'cleaver, meat cleaver, chopper', 'cliff dwelling', 'cloak', 'clog, geta, patten, sabot', 'cocktail shaker', 'coffee mug', 'coffeepot', 'coil, spiral, volute, whorl, helix', 'combination lock', 'computer keyboard, keypad', 'confectionery, confectionary, candy store', 'container ship, containership, container vessel', 'convertible', 'corkscrew, bottle screw', 'cornet, horn, trumpet, trump', 'cowboy boot', 'cowboy hat, ten-gallon hat', 'cradle', 'crane', 'crash helmet', 'crate', 'crib, cot', 'Crock Pot', 'croquet ball', 'crutch', 'cuirass', 'dam, dike, dyke', 'desk', 'desktop computer', 'dial telephone, dial phone', 'diaper, nappy, napkin', 'digital clock', 'digital watch', 'dining table, board', 'dishrag, dishcloth', 'dishwasher, dish washer, dishwashing machine', 'disk brake, disc brake', 'dock, dockage, docking facility', 'dogsled, dog sled, dog sleigh', 'dome', 'doormat, welcome mat', 'drilling platform, offshore rig', 'drum, membranophone, tympan', 'drumstick', 'dumbbell', 'Dutch oven', 'electric fan, blower', 'electric guitar', 'electric locomotive', 'entertainment center', 'envelope', 'espresso maker', 'face powder', 'feather boa, boa', 'file, file cabinet, filing cabinet', 'fireboat', 'fire engine, fire truck', 'fire screen, fireguard', 'flagpole, flagstaff', 'flute, transverse flute', 'folding chair', 'football helmet', 'forklift', 'fountain', 'fountain pen', 'four-poster', 'freight car', 'French horn, horn', 'frying pan, frypan, skillet', 'fur coat', 'garbage truck, dustcart', 'gasmask, respirator, gas helmet', 'gas pump, gasoline pump, petrol pump, island dispenser', 'goblet', 'go-kart', 'golf ball', 'golfcart, golf cart', 'gondola', 'gong, tam-tam', 'gown', 'grand piano, grand', 'greenhouse, nursery, glasshouse', 'grille, radiator grille', 'grocery store, grocery, food market, market', 'guillotine', 'hair slide', 'hair spray', 'half track', 'hammer', 'hamper', 'hand blower, blow dryer, blow drier, hair dryer, hair drier', 'hand-held computer, hand-held microcomputer', 'handkerchief, hankie, hanky, hankey', 'hard disc, hard disk, fixed disk', 'harmonica, mouth organ, harp, mouth harp', 'harp', 'harvester, reaper', 'hatchet', 'holster', 'home theater, home theatre', 'honeycomb', 'hook, claw', 'hoopskirt, crinoline', 'horizontal bar, high bar', 'horse cart, horse-cart', 'hourglass', 'iPod', 'iron, smoothing iron', "jack-o'-lantern", 'jean, blue jean, denim', 'jeep, landrover', 'jersey, T-shirt, tee shirt', 'jigsaw puzzle', 'jinrikisha, ricksha, rickshaw', 'joystick', 'kimono', 'knee pad', 'knot', 'lab coat, laboratory coat', 'ladle', 'lampshade, lamp shade', 'laptop, laptop computer', 'lawn mower, mower', 'lens cap, lens cover', 'letter opener, paper knife, paperknife', 'library', 'lifeboat', 'lighter, light, igniter, ignitor', 'limousine, limo', 'liner, ocean liner', 'lipstick, lip rouge', 'Loafer', 'lotion', 'loudspeaker, speaker, speaker unit, loudspeaker system, speaker system', "loupe, jeweler's loupe", 'lumbermill, sawmill', 'magnetic compass', 'mailbag, postbag', 'mailbox, letter box', 'maillot', 'maillot, tank suit', 'manhole cover', 'maraca', 'marimba, xylophone', 'mask', 'matchstick', 'maypole', 'maze, labyrinth', 'measuring cup', 'medicine chest, medicine cabinet', 'megalith, megalithic structure', 'microphone, mike', 'microwave, microwave oven', 'military uniform', 'milk can', 'minibus', 'miniskirt, mini', 'minivan', 'missile', 'mitten', 'mixing bowl', 'mobile home, manufactured home', 'Model T', 'modem', 'monastery', 'monitor', 'moped', 'mortar', 'mortarboard', 'mosque', 'mosquito net', 'motor scooter, scooter', 'mountain bike, all-terrain bike, off-roader', 'mountain tent', 'mouse, computer mouse', 'mousetrap', 'moving van', 'muzzle', 'nail', 'neck brace', 'necklace', 'nipple', 'notebook, notebook computer', 'obelisk', 'oboe, hautboy, hautbois', 'ocarina, sweet potato', 'odometer, hodometer, mileometer, milometer', 'oil filter', 'organ, pipe organ', 'oscilloscope, scope, cathode-ray oscilloscope, CRO', 'overskirt', 'oxcart', 'oxygen mask', 'packet', 'paddle, boat paddle', 'paddlewheel, paddle wheel', 'padlock', 'paintbrush', "pajama, pyjama, pj's, jammies", 'palace', 'panpipe, pandean pipe, syrinx', 'paper towel', 'parachute, chute', 'parallel bars, bars', 'park bench', 'parking meter', 'passenger car, coach, carriage', 'patio, terrace', 'pay-phone, pay-station', 'pedestal, plinth, footstall', 'pencil box, pencil case', 'pencil sharpener', 'perfume, essence', 'Petri dish', 'photocopier', 'pick, plectrum, plectron', 'pickelhaube', 'picket fence, paling', 'pickup, pickup truck', 'pier', 'piggy bank, penny bank', 'pill bottle', 'pillow', 'ping-pong ball', 'pinwheel', 'pirate, pirate ship', 'pitcher, ewer', "plane, carpenter's plane, woodworking plane", 'planetarium', 'plastic bag', 'plate rack', 'plow, plough', "plunger, plumber's helper", 'Polaroid camera, Polaroid Land camera', 'pole', 'police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria', 'poncho', 'pool table, billiard table, snooker table', 'pop bottle, soda bottle', 'pot, flowerpot', "potter's wheel", 'power drill', 'prayer rug, prayer mat', 'printer', 'prison, prison house', 'projectile, missile', 'projector', 'puck, hockey puck', 'punching bag, punch bag, punching ball, punchball', 'purse', 'quill, quill pen', 'quilt, comforter, comfort, puff', 'racer, race car, racing car', 'racket, racquet', 'radiator', 'radio, wireless', 'radio telescope, radio reflector', 'rain barrel', 'recreational vehicle, RV, R.V.', 'reel', 'reflex camera', 'refrigerator, icebox', 'remote control, remote', 'restaurant, eating house, eating place, eatery', 'revolver, six-gun, six-shooter', 'rifle', 'rocking chair, rocker', 'rotisserie', 'rubber eraser, rubber, pencil eraser', 'rugby ball', 'rule, ruler', 'running shoe', 'safe', 'safety pin', 'saltshaker, salt shaker', 'sandal', 'sarong', 'sax, saxophone', 'scabbard', 'scale, weighing machine', 'school bus', 'schooner', 'scoreboard', 'screen, CRT screen', 'screw', 'screwdriver', 'seat belt, seatbelt', 'sewing machine', 'shield, buckler', 'shoe shop, shoe-shop, shoe store', 'shoji', 'shopping basket', 'shopping cart', 'shovel', 'shower cap', 'shower curtain', 'ski', 'ski mask', 'sleeping bag', 'slide rule, slipstick', 'sliding door', 'slot, one-armed bandit', 'snorkel', 'snowmobile', 'snowplow, snowplough', 'soap dispenser', 'soccer ball', 'sock', 'solar dish, solar collector, solar furnace', 'sombrero', 'soup bowl', 'space bar', 'space heater', 'space shuttle', 'spatula', 'speedboat', "spider web, spider's web", 'spindle', 'sports car, sport car', 'spotlight, spot', 'stage', 'steam locomotive', 'steel arch bridge', 'steel drum', 'stethoscope', 'stole', 'stone wall', 'stopwatch, stop watch', 'stove', 'strainer', 'streetcar, tram, tramcar, trolley, trolley car', 'stretcher', 'studio couch, day bed', 'stupa, tope', 'submarine, pigboat, sub, U-boat', 'suit, suit of clothes', 'sundial', 'sunglass', 'sunglasses, dark glasses, shades', 'sunscreen, sunblock, sun blocker', 'suspension bridge', 'swab, swob, mop', 'sweatshirt', 'swimming trunks, bathing trunks', 'swing', 'switch, electric switch, electrical switch', 'syringe', 'table lamp', 'tank, army tank, armored combat vehicle, armoured combat vehicle', 'tape player', 'teapot', 'teddy, teddy bear', 'television, television system', 'tennis ball', 'thatch, thatched roof', 'theater curtain, theatre curtain', 'thimble', 'thresher, thrasher, threshing machine', 'throne', 'tile roof', 'toaster', 'tobacco shop, tobacconist shop, tobacconist', 'toilet seat', 'torch', 'totem pole', 'tow truck, tow car, wrecker', 'toyshop', 'tractor', 'trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi', 'tray', 'trench coat', 'tricycle, trike, velocipede', 'trimaran', 'tripod', 'triumphal arch', 'trolleybus, trolley coach, trackless trolley', 'trombone', 'tub, vat', 'turnstile', 'typewriter keyboard', 'umbrella', 'unicycle, monocycle', 'upright, upright piano', 'vacuum, vacuum cleaner', 'vase', 'vault', 'velvet', 'vending machine', 'vestment', 'viaduct', 'violin, fiddle', 'volleyball', 'waffle iron', 'wall clock', 'wallet, billfold, notecase, pocketbook', 'wardrobe, closet, press', 'warplane, military plane', 'washbasin, handbasin, washbowl, lavabo, wash-hand basin', 'washer, automatic washer, washing machine', 'water bottle', 'water jug', 'water tower', 'whiskey jug', 'whistle', 'wig', 'window screen', 'window shade', 'Windsor tie', 'wine bottle', 'wing', 'wok', 'wooden spoon', 'wool, woolen, woollen', 'worm fence, snake fence, snake-rail fence, Virginia fence', 'wreck', 'yawl', 'yurt', 'web site, website, internet site, site', 'comic book', 'crossword puzzle, crossword', 'street sign', 'traffic light, traffic signal, stoplight', 'book jacket, dust cover, dust jacket, dust wrapper', 'menu', 'plate', 'guacamole', 'consomme', 'hot pot, hotpot', 'trifle', 'ice cream, icecream', 'ice lolly, lolly, lollipop, popsicle', 'French loaf', 'bagel, beigel', 'pretzel', 'cheeseburger', 'hotdog, hot dog, red hot', 'mashed potato', 'head cabbage', 'broccoli', 'cauliflower', 'zucchini, courgette', 'spaghetti squash', 'acorn squash', 'butternut squash', 'cucumber, cuke', 'artichoke, globe artichoke', 'bell pepper', 'cardoon', 'mushroom', 'Granny Smith', 'strawberry', 'orange', 'lemon', 'fig', 'pineapple, ananas', 'banana', 'jackfruit, jak, jack', 'custard apple', 'pomegranate', 'hay', 'carbonara', 'chocolate sauce, chocolate syrup', 'dough', 'meat loaf, meatloaf', 'pizza, pizza pie', 'potpie', 'burrito', 'red wine', 'espresso', 'cup', 'eggnog', 'alp', 'bubble', 'cliff, drop, drop-off', 'coral reef', 'geyser', 'lakeside, lakeshore', 'promontory, headland, head, foreland', 'sandbar, sand bar', 'seashore, coast, seacoast, sea-coast', 'valley, vale', 'volcano', 'ballplayer, baseball player', 'groom, bridegroom', 'scuba diver', 'rapeseed', 'daisy', "yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum", 'corn', 'acorn', 'hip, rose hip, rosehip', 'buckeye, horse chestnut, conker', 'coral fungus', 'agaric', 'gyromitra', 'stinkhorn, carrion fungus', 'earthstar', 'hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa', 'bolete', 'ear, spike, capitulum', 'toilet tissue, toilet paper, bathroom tissue']
149
+ image_size: 224 # 224 for CLIP
150
+ image_plot_scaling: 2 # 4 for 232 num_channels, 64 for 3000
151
+ channels: 3
152
+ logit_transform: false
153
+ uniform_dequantization: false
154
+ gaussian_dequantization: false
155
+ random_flip: false
156
+ rescaled: false
157
+ num_workers: 4
158
+ tinyImages:
159
+ augm_type: 'none'
160
+ cutout_window: 16
161
+ out_size: 32
162
+ exclude_cifar: true
163
+ exclude_cifar10_1: true
164
+ offset: 0
165
+
166
+
167
+ model:
168
+ sigma_begin: 1 # 50
169
+ num_classes: 1086 #1086 #500 # 232 for non-RATIO mode, 3000 otherwise
170
+ ema: true
171
+ ema_rate: 0.9999
172
+ spec_norm: false
173
+ sigma_dist: geometric
174
+ sigma_end: 0.01
175
+ normalization: InstanceNorm++
176
+ nonlinearity: elu
177
+ ngf: 128
178
+ unet: true
179
+
180
+ optim:
181
+ weight_decay: 0.000
182
+ optimizer: "Adam"
183
+ lr: 0.0001
184
+ beta1: 0.9
185
+ beta2: 0.999
186
+ amsgrad: false
187
+ eps: 0.00000001
188
+ utils:
189
+ device_ids: [0]
190
+ evaluation:
191
+ evaluation_type: 'all_samples_eval' # latex_benchmark, all_samples_eval
192
+ base_folder: 'ACSM/slurm_start_files/exp/logits_evolution/image_samples' #'ACSM/exp/logits_evolution_evaluate/image_samples_IN1000'
193
+ pattern_folder: 'Appendix_plots_*' #'BENCH*' #'FAILURE*apgd*' # # benchmark/ablation : BENCH*, apgd : FAILURE*
194
+ ids: [94] # benchmark/ablation : [37, 72, 94], apgd: [92]
195
+ #[9,37,51,61,66,72,80,85,94] # the best - [5, 11, 20, 56], random out of 100 - [32, 62, 67, 36]
196
+
diffusion_ckpts/256x256_diffusion_uncond.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a37c32fffd316cd494cf3f35b339936debdc1576dad13fe57c42399a5dbc78b1
3
+ size 2211383297
guided_diffusion/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .DS_Store
2
+ __pycache__/
3
+
guided_diffusion/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 OpenAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
guided_diffusion/README.md ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # guided-diffusion
2
+
3
+ This is the codebase for [Diffusion Models Beat GANS on Image Synthesis](http://arxiv.org/abs/2105.05233).
4
+
5
+ This repository is based on [openai/improved-diffusion](https://github.com/openai/improved-diffusion), with modifications for classifier conditioning and architecture improvements.
6
+
7
+ # Download pre-trained models
8
+
9
+ We have released checkpoints for the main models in the paper. Before using these models, please review the corresponding [model card](model-card.md) to understand the intended use and limitations of these models.
10
+
11
+ Here are the download links for each model checkpoint:
12
+
13
+ * 64x64 classifier: [64x64_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64x64_classifier.pt)
14
+ * 64x64 diffusion: [64x64_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64x64_diffusion.pt)
15
+ * 128x128 classifier: [128x128_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128x128_classifier.pt)
16
+ * 128x128 diffusion: [128x128_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128x128_diffusion.pt)
17
+ * 256x256 classifier: [256x256_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_classifier.pt)
18
+ * 256x256 diffusion: [256x256_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion.pt)
19
+ * 256x256 diffusion (not class conditional): [256x256_diffusion_uncond.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt)
20
+ * 512x512 classifier: [512x512_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/512x512_classifier.pt)
21
+ * 512x512 diffusion: [512x512_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/512x512_diffusion.pt)
22
+ * 64x64 -&gt; 256x256 upsampler: [64_256_upsampler.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64_256_upsampler.pt)
23
+ * 128x128 -&gt; 512x512 upsampler: [128_512_upsampler.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128_512_upsampler.pt)
24
+ * LSUN bedroom: [lsun_bedroom.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_bedroom.pt)
25
+ * LSUN cat: [lsun_cat.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_cat.pt)
26
+ * LSUN horse: [lsun_horse.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_horse.pt)
27
+ * LSUN horse (no dropout): [lsun_horse_nodropout.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_horse_nodropout.pt)
28
+
29
+ # Sampling from pre-trained models
30
+
31
+ To sample from these models, you can use the `classifier_sample.py`, `image_sample.py`, and `super_res_sample.py` scripts.
32
+ Here, we provide flags for sampling from all of these models.
33
+ We assume that you have downloaded the relevant model checkpoints into a folder called `models/`.
34
+
35
+ For these examples, we will generate 100 samples with batch size 4. Feel free to change these values.
36
+
37
+ ```
38
+ SAMPLE_FLAGS="--batch_size 4 --num_samples 100 --timestep_respacing 250"
39
+ ```
40
+
41
+ ## Classifier guidance
42
+
43
+ Note for these sampling runs that you can set `--classifier_scale 0` to sample from the base diffusion model.
44
+ You may also use the `image_sample.py` script instead of `classifier_sample.py` in that case.
45
+
46
+ * 64x64 model:
47
+
48
+ ```
49
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --dropout 0.1 --image_size 64 --learn_sigma True --noise_schedule cosine --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --resblock_updown True --use_new_attention_order True --use_fp16 True --use_scale_shift_norm True"
50
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 1.0 --classifier_path models/64x64_classifier.pt --model_path models/64x64_diffusion.pt $SAMPLE_FLAGS
51
+ ```
52
+
53
+ * 128x128 model:
54
+
55
+ ```
56
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 128 --learn_sigma True --noise_schedule linear --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
57
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 0.5 --classifier_path models/128x128_classifier.pt --model_path models/128x128_diffusion.pt $SAMPLE_FLAGS
58
+ ```
59
+
60
+ * 256x256 model:
61
+
62
+ ```
63
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
64
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 1.0 --classifier_path models/256x256_classifier.pt --model_path models/256x256_diffusion.pt $SAMPLE_FLAGS
65
+ ```
66
+
67
+ * 256x256 model (unconditional):
68
+
69
+ ```
70
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
71
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 10.0 --classifier_path models/256x256_classifier.pt --model_path models/256x256_diffusion.pt $SAMPLE_FLAGS
72
+ ```
73
+
74
+ * 512x512 model:
75
+
76
+ ```
77
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 512 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 False --use_scale_shift_norm True"
78
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 4.0 --classifier_path models/512x512_classifier.pt --model_path models/512x512_diffusion.pt $SAMPLE_FLAGS
79
+ ```
80
+
81
+ ## Upsampling
82
+
83
+ For these runs, we assume you have some base samples in a file `64_samples.npz` or `128_samples.npz` for the two respective models.
84
+
85
+ * 64 -&gt; 256:
86
+
87
+ ```
88
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --large_size 256 --small_size 64 --learn_sigma True --noise_schedule linear --num_channels 192 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
89
+ python super_res_sample.py $MODEL_FLAGS --model_path models/64_256_upsampler.pt --base_samples 64_samples.npz $SAMPLE_FLAGS
90
+ ```
91
+
92
+ * 128 -&gt; 512:
93
+
94
+ ```
95
+ MODEL_FLAGS="--attention_resolutions 32,16 --class_cond True --diffusion_steps 1000 --large_size 512 --small_size 128 --learn_sigma True --noise_schedule linear --num_channels 192 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
96
+ python super_res_sample.py $MODEL_FLAGS --model_path models/128_512_upsampler.pt $SAMPLE_FLAGS --base_samples 128_samples.npz
97
+ ```
98
+
99
+ ## LSUN models
100
+
101
+ These models are class-unconditional and correspond to a single LSUN class. Here, we show how to sample from `lsun_bedroom.pt`, but the other two LSUN checkpoints should work as well:
102
+
103
+ ```
104
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --dropout 0.1 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
105
+ python image_sample.py $MODEL_FLAGS --model_path models/lsun_bedroom.pt $SAMPLE_FLAGS
106
+ ```
107
+
108
+ You can sample from `lsun_horse_nodropout.pt` by changing the dropout flag:
109
+
110
+ ```
111
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --dropout 0.0 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
112
+ python image_sample.py $MODEL_FLAGS --model_path models/lsun_horse_nodropout.pt $SAMPLE_FLAGS
113
+ ```
114
+
115
+ Note that for these models, the best samples result from using 1000 timesteps:
116
+
117
+ ```
118
+ SAMPLE_FLAGS="--batch_size 4 --num_samples 100 --timestep_respacing 1000"
119
+ ```
120
+
121
+ # Results
122
+
123
+ This table summarizes our ImageNet results for pure guided diffusion models:
124
+
125
+ | Dataset | FID | Precision | Recall |
126
+ |------------------|------|-----------|--------|
127
+ | ImageNet 64x64 | 2.07 | 0.74 | 0.63 |
128
+ | ImageNet 128x128 | 2.97 | 0.78 | 0.59 |
129
+ | ImageNet 256x256 | 4.59 | 0.82 | 0.52 |
130
+ | ImageNet 512x512 | 7.72 | 0.87 | 0.42 |
131
+
132
+ This table shows the best results for high resolutions when using upsampling and guidance together:
133
+
134
+ | Dataset | FID | Precision | Recall |
135
+ |------------------|------|-----------|--------|
136
+ | ImageNet 256x256 | 3.94 | 0.83 | 0.53 |
137
+ | ImageNet 512x512 | 3.85 | 0.84 | 0.53 |
138
+
139
+ Finally, here are the unguided results on individual LSUN classes:
140
+
141
+ | Dataset | FID | Precision | Recall |
142
+ |--------------|------|-----------|--------|
143
+ | LSUN Bedroom | 1.90 | 0.66 | 0.51 |
144
+ | LSUN Cat | 5.57 | 0.63 | 0.52 |
145
+ | LSUN Horse | 2.57 | 0.71 | 0.55 |
146
+
147
+ # Training models
148
+
149
+ Training diffusion models is described in the [parent repository](https://github.com/openai/improved-diffusion). Training a classifier is similar. We assume you have put training hyperparameters into a `TRAIN_FLAGS` variable, and classifier hyperparameters into a `CLASSIFIER_FLAGS` variable. Then you can run:
150
+
151
+ ```
152
+ mpiexec -n N python scripts/classifier_train.py --data_dir path/to/imagenet $TRAIN_FLAGS $CLASSIFIER_FLAGS
153
+ ```
154
+
155
+ Make sure to divide the batch size in `TRAIN_FLAGS` by the number of MPI processes you are using.
156
+
157
+ Here are flags for training the 128x128 classifier. You can modify these for training classifiers at other resolutions:
158
+
159
+ ```sh
160
+ TRAIN_FLAGS="--iterations 300000 --anneal_lr True --batch_size 256 --lr 3e-4 --save_interval 10000 --weight_decay 0.05"
161
+ CLASSIFIER_FLAGS="--image_size 128 --classifier_attention_resolutions 32,16,8 --classifier_depth 2 --classifier_width 128 --classifier_pool attention --classifier_resblock_updown True --classifier_use_scale_shift_norm True"
162
+ ```
163
+
164
+ For sampling from a 128x128 classifier-guided model, 25 step DDIM:
165
+
166
+ ```sh
167
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --image_size 128 --learn_sigma True --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
168
+ CLASSIFIER_FLAGS="--image_size 128 --classifier_attention_resolutions 32,16,8 --classifier_depth 2 --classifier_width 128 --classifier_pool attention --classifier_resblock_updown True --classifier_use_scale_shift_norm True --classifier_scale 1.0 --classifier_use_fp16 True"
169
+ SAMPLE_FLAGS="--batch_size 4 --num_samples 50000 --timestep_respacing ddim25 --use_ddim True"
170
+ mpiexec -n N python scripts/classifier_sample.py \
171
+ --model_path /path/to/model.pt \
172
+ --classifier_path path/to/classifier.pt \
173
+ $MODEL_FLAGS $CLASSIFIER_FLAGS $SAMPLE_FLAGS
174
+ ```
175
+
176
+ To sample for 250 timesteps without DDIM, replace `--timestep_respacing ddim25` to `--timestep_respacing 250`, and replace `--use_ddim True` with `--use_ddim False`.
guided_diffusion/__init__.py ADDED
File without changes
guided_diffusion/dist_util.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helpers for distributed training.
3
+ """
4
+
5
+ import io
6
+ import os
7
+ import socket
8
+
9
+ import blobfile as bf
10
+ from mpi4py import MPI
11
+ import torch as th
12
+ import torch.distributed as dist
13
+
14
+ # Change this to reflect your cluster layout.
15
+ # The GPU for a given rank is (rank % GPUS_PER_NODE).
16
+ GPUS_PER_NODE = 8
17
+
18
+ SETUP_RETRY_COUNT = 3
19
+
20
+
21
+ def setup_dist():
22
+ """
23
+ Setup a distributed process group.
24
+ """
25
+ if dist.is_initialized():
26
+ return
27
+ os.environ["CUDA_VISIBLE_DEVICES"] = f"{MPI.COMM_WORLD.Get_rank() % GPUS_PER_NODE}"
28
+
29
+ comm = MPI.COMM_WORLD
30
+ backend = "gloo" if not th.cuda.is_available() else "nccl"
31
+
32
+ if backend == "gloo":
33
+ hostname = "localhost"
34
+ else:
35
+ hostname = socket.gethostbyname(socket.getfqdn())
36
+ os.environ["MASTER_ADDR"] = comm.bcast(hostname, root=0)
37
+ os.environ["RANK"] = str(comm.rank)
38
+ os.environ["WORLD_SIZE"] = str(comm.size)
39
+
40
+ port = comm.bcast(_find_free_port(), root=0)
41
+ os.environ["MASTER_PORT"] = str(port)
42
+ dist.init_process_group(backend=backend, init_method="env://")
43
+
44
+
45
+ def dev():
46
+ """
47
+ Get the device to use for torch.distributed.
48
+ """
49
+ if th.cuda.is_available():
50
+ return th.device(f"cuda")
51
+ return th.device("cpu")
52
+
53
+
54
+ def load_state_dict(path, **kwargs):
55
+ """
56
+ Load a PyTorch file without redundant fetches across MPI ranks.
57
+ """
58
+ chunk_size = 2 ** 30 # MPI has a relatively small size limit
59
+ if MPI.COMM_WORLD.Get_rank() == 0:
60
+ with bf.BlobFile(path, "rb") as f:
61
+ data = f.read()
62
+ num_chunks = len(data) // chunk_size
63
+ if len(data) % chunk_size:
64
+ num_chunks += 1
65
+ MPI.COMM_WORLD.bcast(num_chunks)
66
+ for i in range(0, len(data), chunk_size):
67
+ MPI.COMM_WORLD.bcast(data[i : i + chunk_size])
68
+ else:
69
+ num_chunks = MPI.COMM_WORLD.bcast(None)
70
+ data = bytes()
71
+ for _ in range(num_chunks):
72
+ data += MPI.COMM_WORLD.bcast(None)
73
+
74
+ return th.load(io.BytesIO(data), **kwargs)
75
+
76
+
77
+ def sync_params(params):
78
+ """
79
+ Synchronize a sequence of Tensors across ranks from rank 0.
80
+ """
81
+ for p in params:
82
+ with th.no_grad():
83
+ dist.broadcast(p, 0)
84
+
85
+
86
+ def _find_free_port():
87
+ try:
88
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
89
+ s.bind(("", 0))
90
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
91
+ return s.getsockname()[1]
92
+ finally:
93
+ s.close()
guided_diffusion/guided_diffusion/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Codebase for "Improved Denoising Diffusion Probabilistic Models".
3
+ """
guided_diffusion/guided_diffusion/dist_util.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helpers for distributed training.
3
+ """
4
+
5
+ import io
6
+ import os
7
+ import socket
8
+
9
+ import blobfile as bf
10
+ from mpi4py import MPI
11
+ import torch as th
12
+ import torch.distributed as dist
13
+
14
+ # Change this to reflect your cluster layout.
15
+ # The GPU for a given rank is (rank % GPUS_PER_NODE).
16
+ GPUS_PER_NODE = 8
17
+
18
+ SETUP_RETRY_COUNT = 3
19
+
20
+
21
+ def setup_dist():
22
+ """
23
+ Setup a distributed process group.
24
+ """
25
+ if dist.is_initialized():
26
+ return
27
+ os.environ["CUDA_VISIBLE_DEVICES"] = f"{MPI.COMM_WORLD.Get_rank() % GPUS_PER_NODE}"
28
+
29
+ comm = MPI.COMM_WORLD
30
+ backend = "gloo" if not th.cuda.is_available() else "nccl"
31
+
32
+ if backend == "gloo":
33
+ hostname = "localhost"
34
+ else:
35
+ hostname = socket.gethostbyname(socket.getfqdn())
36
+ os.environ["MASTER_ADDR"] = comm.bcast(hostname, root=0)
37
+ os.environ["RANK"] = str(comm.rank)
38
+ os.environ["WORLD_SIZE"] = str(comm.size)
39
+
40
+ port = comm.bcast(_find_free_port(), root=0)
41
+ os.environ["MASTER_PORT"] = str(port)
42
+ dist.init_process_group(backend=backend, init_method="env://")
43
+
44
+
45
+ def dev():
46
+ """
47
+ Get the device to use for torch.distributed.
48
+ """
49
+ if th.cuda.is_available():
50
+ return th.device(f"cuda")
51
+ return th.device("cpu")
52
+
53
+
54
+ def load_state_dict(path, **kwargs):
55
+ """
56
+ Load a PyTorch file without redundant fetches across MPI ranks.
57
+ """
58
+ chunk_size = 2 ** 30 # MPI has a relatively small size limit
59
+ if MPI.COMM_WORLD.Get_rank() == 0:
60
+ with bf.BlobFile(path, "rb") as f:
61
+ data = f.read()
62
+ num_chunks = len(data) // chunk_size
63
+ if len(data) % chunk_size:
64
+ num_chunks += 1
65
+ MPI.COMM_WORLD.bcast(num_chunks)
66
+ for i in range(0, len(data), chunk_size):
67
+ MPI.COMM_WORLD.bcast(data[i : i + chunk_size])
68
+ else:
69
+ num_chunks = MPI.COMM_WORLD.bcast(None)
70
+ data = bytes()
71
+ for _ in range(num_chunks):
72
+ data += MPI.COMM_WORLD.bcast(None)
73
+
74
+ return th.load(io.BytesIO(data), **kwargs)
75
+
76
+
77
+ def sync_params(params):
78
+ """
79
+ Synchronize a sequence of Tensors across ranks from rank 0.
80
+ """
81
+ for p in params:
82
+ with th.no_grad():
83
+ dist.broadcast(p, 0)
84
+
85
+
86
+ def _find_free_port():
87
+ try:
88
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
89
+ s.bind(("", 0))
90
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
91
+ return s.getsockname()[1]
92
+ finally:
93
+ s.close()
guided_diffusion/guided_diffusion/fp16_util.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helpers to train with 16-bit precision.
3
+ """
4
+
5
+ import numpy as np
6
+ import torch as th
7
+ import torch.nn as nn
8
+ from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
9
+
10
+ from . import logger
11
+
12
+ INITIAL_LOG_LOSS_SCALE = 20.0
13
+
14
+
15
+ def convert_module_to_f16(l):
16
+ """
17
+ Convert primitive modules to float16.
18
+ """
19
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
20
+ l.weight.data = l.weight.data.half()
21
+ if l.bias is not None:
22
+ l.bias.data = l.bias.data.half()
23
+
24
+
25
+ def convert_module_to_f32(l):
26
+ """
27
+ Convert primitive modules to float32, undoing convert_module_to_f16().
28
+ """
29
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
30
+ l.weight.data = l.weight.data.float()
31
+ if l.bias is not None:
32
+ l.bias.data = l.bias.data.float()
33
+
34
+
35
+ def make_master_params(param_groups_and_shapes):
36
+ """
37
+ Copy model parameters into a (differently-shaped) list of full-precision
38
+ parameters.
39
+ """
40
+ master_params = []
41
+ for param_group, shape in param_groups_and_shapes:
42
+ master_param = nn.Parameter(
43
+ _flatten_dense_tensors(
44
+ [param.detach().float() for (_, param) in param_group]
45
+ ).view(shape)
46
+ )
47
+ master_param.requires_grad = True
48
+ master_params.append(master_param)
49
+ return master_params
50
+
51
+
52
+ def model_grads_to_master_grads(param_groups_and_shapes, master_params):
53
+ """
54
+ Copy the gradients from the model parameters into the master parameters
55
+ from make_master_params().
56
+ """
57
+ for master_param, (param_group, shape) in zip(
58
+ master_params, param_groups_and_shapes
59
+ ):
60
+ master_param.grad = _flatten_dense_tensors(
61
+ [param_grad_or_zeros(param) for (_, param) in param_group]
62
+ ).view(shape)
63
+
64
+
65
+ def master_params_to_model_params(param_groups_and_shapes, master_params):
66
+ """
67
+ Copy the master parameter data back into the model parameters.
68
+ """
69
+ # Without copying to a list, if a generator is passed, this will
70
+ # silently not copy any parameters.
71
+ for master_param, (param_group, _) in zip(master_params, param_groups_and_shapes):
72
+ for (_, param), unflat_master_param in zip(
73
+ param_group, unflatten_master_params(param_group, master_param.view(-1))
74
+ ):
75
+ param.detach().copy_(unflat_master_param)
76
+
77
+
78
+ def unflatten_master_params(param_group, master_param):
79
+ return _unflatten_dense_tensors(master_param, [param for (_, param) in param_group])
80
+
81
+
82
+ def get_param_groups_and_shapes(named_model_params):
83
+ named_model_params = list(named_model_params)
84
+ scalar_vector_named_params = (
85
+ [(n, p) for (n, p) in named_model_params if p.ndim <= 1],
86
+ (-1),
87
+ )
88
+ matrix_named_params = (
89
+ [(n, p) for (n, p) in named_model_params if p.ndim > 1],
90
+ (1, -1),
91
+ )
92
+ return [scalar_vector_named_params, matrix_named_params]
93
+
94
+
95
+ def master_params_to_state_dict(
96
+ model, param_groups_and_shapes, master_params, use_fp16
97
+ ):
98
+ if use_fp16:
99
+ state_dict = model.state_dict()
100
+ for master_param, (param_group, _) in zip(
101
+ master_params, param_groups_and_shapes
102
+ ):
103
+ for (name, _), unflat_master_param in zip(
104
+ param_group, unflatten_master_params(param_group, master_param.view(-1))
105
+ ):
106
+ assert name in state_dict
107
+ state_dict[name] = unflat_master_param
108
+ else:
109
+ state_dict = model.state_dict()
110
+ for i, (name, _value) in enumerate(model.named_parameters()):
111
+ assert name in state_dict
112
+ state_dict[name] = master_params[i]
113
+ return state_dict
114
+
115
+
116
+ def state_dict_to_master_params(model, state_dict, use_fp16):
117
+ if use_fp16:
118
+ named_model_params = [
119
+ (name, state_dict[name]) for name, _ in model.named_parameters()
120
+ ]
121
+ param_groups_and_shapes = get_param_groups_and_shapes(named_model_params)
122
+ master_params = make_master_params(param_groups_and_shapes)
123
+ else:
124
+ master_params = [state_dict[name] for name, _ in model.named_parameters()]
125
+ return master_params
126
+
127
+
128
+ def zero_master_grads(master_params):
129
+ for param in master_params:
130
+ param.grad = None
131
+
132
+
133
+ def zero_grad(model_params):
134
+ for param in model_params:
135
+ # Taken from https://pytorch.org/docs/stable/_modules/torch/optim/optimizer.html#Optimizer.add_param_group
136
+ if param.grad is not None:
137
+ param.grad.detach_()
138
+ param.grad.zero_()
139
+
140
+
141
+ def param_grad_or_zeros(param):
142
+ if param.grad is not None:
143
+ return param.grad.data.detach()
144
+ else:
145
+ return th.zeros_like(param)
146
+
147
+
148
+ class MixedPrecisionTrainer:
149
+ def __init__(
150
+ self,
151
+ *,
152
+ model,
153
+ use_fp16=False,
154
+ fp16_scale_growth=1e-3,
155
+ initial_lg_loss_scale=INITIAL_LOG_LOSS_SCALE,
156
+ ):
157
+ self.model = model
158
+ self.use_fp16 = use_fp16
159
+ self.fp16_scale_growth = fp16_scale_growth
160
+
161
+ self.model_params = list(self.model.parameters())
162
+ self.master_params = self.model_params
163
+ self.param_groups_and_shapes = None
164
+ self.lg_loss_scale = initial_lg_loss_scale
165
+
166
+ if self.use_fp16:
167
+ self.param_groups_and_shapes = get_param_groups_and_shapes(
168
+ self.model.named_parameters()
169
+ )
170
+ self.master_params = make_master_params(self.param_groups_and_shapes)
171
+ self.model.convert_to_fp16()
172
+
173
+ def zero_grad(self):
174
+ zero_grad(self.model_params)
175
+
176
+ def backward(self, loss: th.Tensor):
177
+ if self.use_fp16:
178
+ loss_scale = 2 ** self.lg_loss_scale
179
+ (loss * loss_scale).backward()
180
+ else:
181
+ loss.backward()
182
+
183
+ def optimize(self, opt: th.optim.Optimizer):
184
+ if self.use_fp16:
185
+ return self._optimize_fp16(opt)
186
+ else:
187
+ return self._optimize_normal(opt)
188
+
189
+ def _optimize_fp16(self, opt: th.optim.Optimizer):
190
+ logger.logkv_mean("lg_loss_scale", self.lg_loss_scale)
191
+ model_grads_to_master_grads(self.param_groups_and_shapes, self.master_params)
192
+ grad_norm, param_norm = self._compute_norms(grad_scale=2 ** self.lg_loss_scale)
193
+ if check_overflow(grad_norm):
194
+ self.lg_loss_scale -= 1
195
+ logger.log(f"Found NaN, decreased lg_loss_scale to {self.lg_loss_scale}")
196
+ zero_master_grads(self.master_params)
197
+ return False
198
+
199
+ logger.logkv_mean("grad_norm", grad_norm)
200
+ logger.logkv_mean("param_norm", param_norm)
201
+
202
+ self.master_params[0].grad.mul_(1.0 / (2 ** self.lg_loss_scale))
203
+ opt.step()
204
+ zero_master_grads(self.master_params)
205
+ master_params_to_model_params(self.param_groups_and_shapes, self.master_params)
206
+ self.lg_loss_scale += self.fp16_scale_growth
207
+ return True
208
+
209
+ def _optimize_normal(self, opt: th.optim.Optimizer):
210
+ grad_norm, param_norm = self._compute_norms()
211
+ logger.logkv_mean("grad_norm", grad_norm)
212
+ logger.logkv_mean("param_norm", param_norm)
213
+ opt.step()
214
+ return True
215
+
216
+ def _compute_norms(self, grad_scale=1.0):
217
+ grad_norm = 0.0
218
+ param_norm = 0.0
219
+ for p in self.master_params:
220
+ with th.no_grad():
221
+ param_norm += th.norm(p, p=2, dtype=th.float32).item() ** 2
222
+ if p.grad is not None:
223
+ grad_norm += th.norm(p.grad, p=2, dtype=th.float32).item() ** 2
224
+ return np.sqrt(grad_norm) / grad_scale, np.sqrt(param_norm)
225
+
226
+ def master_params_to_state_dict(self, master_params):
227
+ return master_params_to_state_dict(
228
+ self.model, self.param_groups_and_shapes, master_params, self.use_fp16
229
+ )
230
+
231
+ def state_dict_to_master_params(self, state_dict):
232
+ return state_dict_to_master_params(self.model, state_dict, self.use_fp16)
233
+
234
+
235
+ def check_overflow(value):
236
+ return (value == float("inf")) or (value == -float("inf")) or (value != value)
guided_diffusion/guided_diffusion/gaussian_diffusion.py ADDED
@@ -0,0 +1,1252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code started out as a PyTorch port of Ho et al's diffusion models:
3
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py
4
+
5
+ Docstrings have been added, as well as DDIM sampling and a new collection of beta schedules.
6
+ """
7
+
8
+ import enum
9
+ import math
10
+
11
+ import numpy as np
12
+ import torch # TODO: I know this is messy, should clean up later
13
+ import torch as th
14
+ import random
15
+ import matplotlib.pyplot as plt
16
+
17
+ from .nn import mean_flat
18
+ from .losses import normal_kl, discretized_gaussian_log_likelihood
19
+ from tqdm import tqdm
20
+
21
+
22
+ def compute_alpha(beta, t):
23
+ if isinstance(beta, np.ndarray):
24
+ beta = torch.Tensor(beta)
25
+ beta = torch.cat([torch.zeros(1).to(beta.device), beta], dim=0)
26
+ t = t.to(beta.device)
27
+ a = (1 - beta).cumprod(dim=0).index_select(0, t + 1).view(-1, 1, 1, 1)
28
+ return a.to(beta.device)
29
+
30
+
31
+ def show_tensor(img): # (3, 256, 256)
32
+ img = img.detach().cpu().numpy()
33
+ img = np.transpose(img, (1,2,0))
34
+ plt.imshow(img)
35
+ plt.show()
36
+
37
+
38
+ def L1_projection(x2, y2, eps1):
39
+ '''
40
+ x2: center of the L1 ball (bs x input_dim)
41
+ y2: current perturbation (x2 + y2 is the point to be projected)
42
+ eps1: radius of the L1 ball
43
+
44
+ output: delta s.th. ||y2 + delta||_1 <= eps1
45
+ and 0 <= x2 + y2 + delta <= 1
46
+ '''
47
+
48
+ x = x2.clone().float().view(x2.shape[0], -1)
49
+ y = y2.clone().float().view(y2.shape[0], -1)
50
+ sigma = y.clone().sign()
51
+ u = th.min(1 - x - y, x + y)
52
+ # u = th.min(u, epsinf - th.clone(y).abs())
53
+ u = th.min(th.zeros_like(y), u)
54
+ l = -th.clone(y).abs()
55
+ d = u.clone()
56
+
57
+ bs, indbs = th.sort(-th.cat((u, l), 1), dim=1)
58
+ bs2 = th.cat((bs[:, 1:], th.zeros(bs.shape[0], 1).to(bs.device)), 1)
59
+
60
+ inu = 2 * (indbs < u.shape[1]).float() - 1
61
+ size1 = inu.cumsum(dim=1)
62
+
63
+ s1 = -u.sum(dim=1)
64
+
65
+ c = eps1 - y.clone().abs().sum(dim=1)
66
+ c5 = s1 + c < 0
67
+ c2 = c5.nonzero().squeeze(1)
68
+
69
+ s = s1.unsqueeze(-1) + th.cumsum((bs2 - bs) * size1, dim=1)
70
+
71
+ if c2.nelement != 0:
72
+
73
+ lb = th.zeros_like(c2).float()
74
+ ub = th.ones_like(lb) * (bs.shape[1] - 1)
75
+
76
+ # print(c2.shape, lb.shape)
77
+
78
+ nitermax = th.ceil(th.log2(th.tensor(bs.shape[1]).float()))
79
+ counter2 = th.zeros_like(lb).long()
80
+ counter = 0
81
+
82
+ while counter < nitermax:
83
+ counter4 = th.floor((lb + ub) / 2.)
84
+ counter2 = counter4.type(th.LongTensor)
85
+
86
+ c8 = s[c2, counter2] + c[c2] < 0
87
+ ind3 = c8.nonzero().squeeze(1)
88
+ ind32 = (~c8).nonzero().squeeze(1)
89
+ if ind3.nelement != 0:
90
+ lb[ind3] = counter4[ind3]
91
+ if ind32.nelement != 0:
92
+ ub[ind32] = counter4[ind32]
93
+
94
+ counter += 1
95
+
96
+ lb2 = lb.long()
97
+ alpha = (-s[c2, lb2] - c[c2]) / size1[c2, lb2 + 1] + bs2[c2, lb2]
98
+ d[c2] = -th.min(th.max(-u[c2], alpha.unsqueeze(-1)), -l[c2])
99
+
100
+ return (sigma * d).view(x2.shape)
101
+
102
+ def project_perturbation(perturbation, eps, p, center=None):
103
+ if p in ['inf', 'linf', 'Linf']:
104
+ pert_normalized = th.clamp(perturbation, -eps, eps)
105
+ return pert_normalized
106
+ elif p in [2, 2.0, 'l2', 'L2', '2']:
107
+ print('l2 renorm')
108
+ pert_normalized = th.renorm(perturbation, p=2, dim=0, maxnorm=eps)
109
+ return pert_normalized
110
+ elif p in [1, 1.0, 'l1', 'L1', '1']:
111
+ ##pert_normalized = project_onto_l1_ball(perturbation, eps)
112
+ ##return pert_normalized
113
+ pert_normalized = L1_projection(center, perturbation, eps)
114
+ return perturbation + pert_normalized
115
+ #elif p in ['LPIPS']:
116
+ # pert_normalized = project_onto_LPIPS_ball(perturbation, eps)
117
+ else:
118
+ raise NotImplementedError('Projection only supports l1, l2 and inf norm')
119
+
120
+ def get_named_beta_schedule(schedule_name, num_diffusion_timesteps):
121
+ """
122
+ Get a pre-defined beta schedule for the given name.
123
+
124
+ The beta schedule library consists of beta schedules which remain similar
125
+ in the limit of num_diffusion_timesteps.
126
+ Beta schedules may be added, but should not be removed or changed once
127
+ they are committed to maintain backwards compatibility.
128
+ """
129
+ if schedule_name == "linear":
130
+ # Linear schedule from Ho et al, extended to work for any number of
131
+ # diffusion steps.
132
+ scale = 1000 / num_diffusion_timesteps
133
+ beta_start = scale * 0.0001
134
+ beta_end = scale * 0.02
135
+ return np.linspace(beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64)
136
+ elif schedule_name == "cosine":
137
+ return betas_for_alpha_bar(
138
+ num_diffusion_timesteps, lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
139
+ )
140
+ else:
141
+ raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
142
+
143
+
144
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
145
+ """
146
+ Create a beta schedule that discretizes the given alpha_t_bar function,
147
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
148
+
149
+ :param num_diffusion_timesteps: the number of betas to produce.
150
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
151
+ produces the cumulative product of (1-beta) up to that
152
+ part of the diffusion process.
153
+ :param max_beta: the maximum beta to use; use values lower than 1 to
154
+ prevent singularities.
155
+ """
156
+ betas = []
157
+ for i in range(num_diffusion_timesteps):
158
+ t1 = i / num_diffusion_timesteps
159
+ t2 = (i + 1) / num_diffusion_timesteps
160
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
161
+ return np.array(betas)
162
+
163
+
164
+ class ModelMeanType(enum.Enum):
165
+ """
166
+ Which type of output the model predicts.
167
+ """
168
+
169
+ PREVIOUS_X = enum.auto() # the model predicts x_{t-1}
170
+ START_X = enum.auto() # the model predicts x_0
171
+ EPSILON = enum.auto() # the model predicts epsilon
172
+
173
+
174
+ class ModelVarType(enum.Enum):
175
+ """
176
+ What is used as the model's output variance.
177
+
178
+ The LEARNED_RANGE option has been added to allow the model to predict
179
+ values between FIXED_SMALL and FIXED_LARGE, making its job easier.
180
+ """
181
+
182
+ LEARNED = enum.auto()
183
+ FIXED_SMALL = enum.auto()
184
+ FIXED_LARGE = enum.auto()
185
+ LEARNED_RANGE = enum.auto()
186
+
187
+
188
+ class LossType(enum.Enum):
189
+ MSE = enum.auto() # use raw MSE loss (and KL when learning variances)
190
+ RESCALED_MSE = enum.auto() # use raw MSE loss (with RESCALED_KL when learning variances)
191
+ KL = enum.auto() # use the variational lower-bound
192
+ RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB
193
+
194
+ def is_vb(self):
195
+ return self == LossType.KL or self == LossType.RESCALED_KL
196
+
197
+
198
+ class GaussianDiffusion:
199
+ """
200
+ Utilities for training and sampling diffusion models.
201
+
202
+ Ported directly from here, and then adapted over time to further experimentation.
203
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42
204
+
205
+ :param betas: a 1-D numpy array of betas for each diffusion timestep,
206
+ starting at T and going to 1.
207
+ :param model_mean_type: a ModelMeanType determining what the model outputs.
208
+ :param model_var_type: a ModelVarType determining how variance is output.
209
+ :param loss_type: a LossType determining the loss function to use.
210
+ :param rescale_timesteps: if True, pass floating point timesteps into the
211
+ model so that they are always scaled like in the
212
+ original paper (0 to 1000).
213
+ """
214
+
215
+ def __init__(
216
+ self, *, betas, model_mean_type, model_var_type, loss_type, rescale_timesteps=False,
217
+ ):
218
+ self.model_mean_type = model_mean_type
219
+ self.model_var_type = model_var_type
220
+ self.loss_type = loss_type
221
+ self.rescale_timesteps = rescale_timesteps
222
+
223
+ # Use float64 for accuracy.
224
+ betas = np.array(betas, dtype=np.float64)
225
+ self.betas = betas
226
+ assert len(betas.shape) == 1, "betas must be 1-D"
227
+ assert (betas > 0).all() and (betas <= 1).all()
228
+
229
+ self.num_timesteps = int(betas.shape[0])
230
+
231
+ alphas = 1.0 - betas
232
+ self.alphas_cumprod = np.cumprod(alphas, axis=0)
233
+ self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1])
234
+ self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0)
235
+ assert self.alphas_cumprod_prev.shape == (self.num_timesteps,)
236
+
237
+ # calculations for diffusion q(x_t | x_{t-1}) and others
238
+ self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod)
239
+ self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod)
240
+ self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod)
241
+ self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod)
242
+ self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1)
243
+
244
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
245
+ self.posterior_variance = (
246
+ betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
247
+ )
248
+ # log calculation clipped because the posterior variance is 0 at the
249
+ # beginning of the diffusion chain.
250
+ self.posterior_log_variance_clipped = np.log(
251
+ np.append(self.posterior_variance[1], self.posterior_variance[1:])
252
+ )
253
+ self.posterior_mean_coef1 = (
254
+ betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
255
+ )
256
+ self.posterior_mean_coef2 = (
257
+ (1.0 - self.alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - self.alphas_cumprod)
258
+ )
259
+
260
+ self.applied_noise = None
261
+
262
+ def q_mean_variance(self, x_start, t):
263
+ """
264
+ Get the distribution q(x_t | x_0).
265
+
266
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
267
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
268
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
269
+ """
270
+ mean = _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
271
+ variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
272
+ log_variance = _extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
273
+ return mean, variance, log_variance
274
+
275
+ def q_sample(self, x_start, t, noise=None):
276
+ """
277
+ Diffuse the data for a given number of diffusion steps.
278
+
279
+ In other words, sample from q(x_t | x_0).
280
+
281
+ :param x_start: the initial data batch.
282
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
283
+ :param noise: if specified, the split-out normal noise.
284
+ :return: A noisy version of x_start.
285
+ """
286
+ if noise is None:
287
+ noise = th.randn_like(x_start)
288
+ assert noise.shape == x_start.shape
289
+ a = _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
290
+ b = _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
291
+ out = a + b
292
+ return out
293
+
294
+ def q_posterior_mean_variance(self, x_start, x_t, t):
295
+ """
296
+ Compute the mean and variance of the diffusion posterior:
297
+
298
+ q(x_{t-1} | x_t, x_0)
299
+
300
+ """
301
+ assert x_start.shape == x_t.shape
302
+ posterior_mean = (
303
+ _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start
304
+ + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
305
+ )
306
+ posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape)
307
+ posterior_log_variance_clipped = _extract_into_tensor(
308
+ self.posterior_log_variance_clipped, t, x_t.shape
309
+ )
310
+ assert (
311
+ posterior_mean.shape[0]
312
+ == posterior_variance.shape[0]
313
+ == posterior_log_variance_clipped.shape[0]
314
+ == x_start.shape[0]
315
+ )
316
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
317
+
318
+ def p_mean_variance(self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None):
319
+ """
320
+ Apply the model to get p(x_{t-1} | x_t), as well as a prediction of
321
+ the initial x, x_0.
322
+
323
+ :param model: the model, which takes a signal and a batch of timesteps
324
+ as input.
325
+ :param x: the [N x C x ...] tensor at time t.
326
+ :param t: a 1-D Tensor of timesteps.
327
+ :param clip_denoised: if True, clip the denoised signal into [-1, 1].
328
+ :param denoised_fn: if not None, a function which applies to the
329
+ x_start prediction before it is used to sample. Applies before
330
+ clip_denoised.
331
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
332
+ pass to the model. This can be used for conditioning.
333
+ :return: a dict with the following keys:
334
+ - 'mean': the model mean output.
335
+ - 'variance': the model variance output.
336
+ - 'log_variance': the log of 'variance'.
337
+ - 'pred_xstart': the prediction for x_0.
338
+ """
339
+ if model_kwargs is None:
340
+ model_kwargs = {}
341
+
342
+ B, C = x.shape[:2]
343
+ assert t.shape == (B,)
344
+
345
+ if "middle_out" not in model_kwargs:
346
+ model_kwargs["middle_out"] = False
347
+
348
+ if model_kwargs["middle_out"]:
349
+ model_output, middle_out = model(x, self._scale_timesteps(t), **model_kwargs)
350
+ else:
351
+ model_output = model(x, self._scale_timesteps(t), **model_kwargs)
352
+ middle_out = None
353
+
354
+ del model_kwargs["middle_out"]
355
+
356
+
357
+ if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]:
358
+ assert model_output.shape == (B, C * 2, *x.shape[2:])
359
+ model_output, model_var_values = th.split(model_output, C, dim=1)
360
+ if self.model_var_type == ModelVarType.LEARNED:
361
+ model_log_variance = model_var_values
362
+ model_variance = th.exp(model_log_variance)
363
+ else:
364
+ min_log = _extract_into_tensor(self.posterior_log_variance_clipped, t, x.shape)
365
+ max_log = _extract_into_tensor(np.log(self.betas), t, x.shape)
366
+ # The model_var_values is [-1, 1] for [min_var, max_var].
367
+ frac = (model_var_values + 1) / 2
368
+ model_log_variance = frac * max_log + (1 - frac) * min_log
369
+ model_variance = th.exp(model_log_variance)
370
+ else:
371
+ model_variance, model_log_variance = {
372
+ # for fixedlarge, we set the initial (log-)variance like so
373
+ # to get a better decoder log likelihood.
374
+ ModelVarType.FIXED_LARGE: (
375
+ np.append(self.posterior_variance[1], self.betas[1:]),
376
+ np.log(np.append(self.posterior_variance[1], self.betas[1:])),
377
+ ),
378
+ ModelVarType.FIXED_SMALL: (
379
+ self.posterior_variance,
380
+ self.posterior_log_variance_clipped,
381
+ ),
382
+ }[self.model_var_type]
383
+ model_variance = _extract_into_tensor(model_variance, t, x.shape)
384
+ model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape)
385
+
386
+ def process_xstart(x):
387
+ if denoised_fn is not None:
388
+ x = denoised_fn(x)
389
+ if clip_denoised:
390
+ return x.clamp(-1, 1)
391
+ return x
392
+
393
+ if self.model_mean_type == ModelMeanType.PREVIOUS_X:
394
+ pred_xstart = process_xstart(
395
+ self._predict_xstart_from_xprev(x_t=x, t=t, xprev=model_output)
396
+ )
397
+ model_mean = model_output
398
+ elif self.model_mean_type in [ModelMeanType.START_X, ModelMeanType.EPSILON]:
399
+ if self.model_mean_type == ModelMeanType.START_X:
400
+ pred_xstart = process_xstart(model_output)
401
+ else:
402
+ pred_xstart = process_xstart(
403
+ self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)
404
+ )
405
+ model_mean, _, _ = self.q_posterior_mean_variance(x_start=pred_xstart, x_t=x, t=t)
406
+ else:
407
+ raise NotImplementedError(self.model_mean_type)
408
+
409
+ assert model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape
410
+ return {
411
+ "mean": model_mean,
412
+ "variance": model_variance,
413
+ "log_variance": model_log_variance,
414
+ "pred_xstart": pred_xstart,
415
+ "model_output": model_output,
416
+ "middle_out": middle_out
417
+ }
418
+
419
+ def _predict_xstart_from_eps(self, x_t, t, eps):
420
+ assert x_t.shape == eps.shape
421
+ return (
422
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
423
+ - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps
424
+ )
425
+
426
+ def _predict_xstart_from_xprev(self, x_t, t, xprev):
427
+ assert x_t.shape == xprev.shape
428
+ return ( # (xprev - coef2*x_t) / coef1
429
+ _extract_into_tensor(1.0 / self.posterior_mean_coef1, t, x_t.shape) * xprev
430
+ - _extract_into_tensor(
431
+ self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape
432
+ )
433
+ * x_t
434
+ )
435
+
436
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
437
+ return (
438
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart
439
+ ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
440
+
441
+ def _scale_timesteps(self, t):
442
+ if self.rescale_timesteps:
443
+ return t.float() * (1000.0 / self.num_timesteps)
444
+ return t
445
+
446
+ def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
447
+ """
448
+ Compute the mean for the previous step, given a function cond_fn that
449
+ computes the gradient of a conditional log probability with respect to
450
+ x. In particular, cond_fn computes grad(log(p(y|x))), and we want to
451
+ condition on y.
452
+
453
+ This uses the conditioning strategy from Sohl-Dickstein et al. (2015).
454
+ """
455
+ model_kwargs['eps'] = p_mean_var['model_output']
456
+ #model_kwargs['variance'] = p_mean_var["variance"]
457
+ gradient = cond_fn(x, self._scale_timesteps(t), **model_kwargs)
458
+ del model_kwargs['eps']#, model_kwargs['variance']
459
+ #gradient /= gradient.view(x.shape[0], -1).norm(p=2, dim=1).view(x.shape[0], 1, 1, 1)
460
+ new_mean = p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float() #* 200
461
+ del gradient
462
+ return new_mean, p_mean_var["variance"]
463
+
464
+ def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
465
+ """
466
+ Compute what the p_mean_variance output would have been, should the
467
+ model's score function be conditioned by cond_fn.
468
+
469
+ See condition_mean() for details on cond_fn.
470
+
471
+ Unlike condition_mean(), this instead uses the conditioning strategy
472
+ from Song et al (2020).
473
+ """
474
+ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
475
+
476
+
477
+ eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"])
478
+ model_kwargs['eps'] = p_mean_var['model_output']
479
+ gradient = cond_fn(x, self._scale_timesteps(t), **model_kwargs)
480
+ del model_kwargs['eps']
481
+
482
+ eps = eps - (1 - alpha_bar).sqrt() * gradient.float()
483
+ del gradient
484
+ out = p_mean_var.copy()
485
+ out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps)
486
+ out["mean"], _, _ = self.q_posterior_mean_variance(x_start=out["pred_xstart"], x_t=x, t=t)
487
+
488
+ return out, (1 - alpha_bar).sqrt()
489
+
490
+ def p_sample(
491
+ self, model, x, t, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None,
492
+ ):
493
+ """
494
+ Sample x_{t-1} from the model at the given timestep.
495
+
496
+ :param model: the model to sample from.
497
+ :param x: the current tensor at x_{t-1}.
498
+ :param t: the value of t, starting at 0 for the first diffusion step.
499
+ :param clip_denoised: if True, clip the x_start prediction to [-1, 1].
500
+ :param denoised_fn: if not None, a function which applies to the
501
+ x_start prediction before it is used to sample.
502
+ :param cond_fn: if not None, this is a gradient function that acts
503
+ similarly to the model.
504
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
505
+ pass to the model. This can be used for conditioning.
506
+ :return: a dict containing the following keys:
507
+ - 'sample': a random sample from the model.
508
+ - 'pred_xstart': a prediction of x_0.
509
+ """
510
+ out = self.p_mean_variance(
511
+ model,
512
+ x,
513
+ t,
514
+ clip_denoised=clip_denoised,
515
+ denoised_fn=denoised_fn,
516
+ model_kwargs=model_kwargs,
517
+ )
518
+ noise = th.randn_like(x)
519
+ nonzero_mask = (
520
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
521
+ ) # no noise when t == 0
522
+ if cond_fn is not None:
523
+ out["mean"], factor_ = self.condition_mean(cond_fn, out, x, t, model_kwargs=model_kwargs)
524
+ sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise
525
+ # return {"sample": sample, "pred_xstart": out["pred_xstart"], "factor_": factor_}
526
+ return {"sample": sample, "pred_xstart": out["pred_xstart"]}
527
+
528
+ def p_sample_loop(
529
+ self,
530
+ model,
531
+ shape,
532
+ noise=None,
533
+ clip_denoised=True,
534
+ denoised_fn=None,
535
+ cond_fn=None,
536
+ model_kwargs=None,
537
+ device=None,
538
+ progress=False,
539
+ skip_timesteps=0,
540
+ init_image=None,
541
+ randomize_class=False,
542
+ resizers=None,
543
+ range_t=0,
544
+
545
+ ):
546
+ """
547
+ Generate samples from the model.
548
+
549
+ :param model: the model module.
550
+ :param shape: the shape of the samples, (N, C, H, W).
551
+ :param noise: if specified, the noise from the encoder to sample.
552
+ Should be of the same shape as `shape`.
553
+ :param clip_denoised: if True, clip x_start predictions to [-1, 1].
554
+ :param denoised_fn: if not None, a function which applies to the
555
+ x_start prediction before it is used to sample.
556
+ :param cond_fn: if not None, this is a gradient function that acts
557
+ similarly to the model.
558
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
559
+ pass to the model. This can be used for conditioning.
560
+ :param device: if specified, the device to create the samples on.
561
+ If not specified, use a model parameter's device.
562
+ :param progress: if True, show a tqdm progress bar.
563
+ :return: a non-differentiable batch of samples.
564
+ """
565
+ final = None
566
+ for sample in self.p_sample_loop_progressive(
567
+ model,
568
+ shape,
569
+ noise=noise,
570
+ clip_denoised=clip_denoised,
571
+ denoised_fn=denoised_fn,
572
+ cond_fn=cond_fn,
573
+ model_kwargs=model_kwargs,
574
+ device=device,
575
+ progress=progress,
576
+ skip_timesteps=skip_timesteps,
577
+ init_image=init_image,
578
+ randomize_class=randomize_class,
579
+ resizers=resizers,
580
+ range_t=range_t
581
+ ):
582
+ final = sample
583
+ return final["sample"]
584
+
585
+ def p_sample_loop_progressive(
586
+ self,
587
+ model,
588
+ shape,
589
+ noise=None,
590
+ clip_denoised=True,
591
+ denoised_fn=None,
592
+ cond_fn=None,
593
+ model_kwargs=None,
594
+ device=None,
595
+ progress=True,
596
+ skip_timesteps=0,
597
+ init_image=None,
598
+ postprocess_fn=None,
599
+ randomize_class=False,
600
+ resizers=None,
601
+ range_t=0,
602
+ eps_project=30,
603
+ ilvr_multi=0,
604
+ seed=1
605
+ ):
606
+
607
+ th.manual_seed(seed)
608
+ random.seed(seed)
609
+ np.random.seed(seed)
610
+ """
611
+ Generate samples from the model and yield intermediate samples from
612
+ each timestep of diffusion.
613
+
614
+ Arguments are the same as p_sample_loop().
615
+ Returns a generator over dicts, where each dict is the return value of
616
+ p_sample().
617
+ """
618
+
619
+ if resizers is not None:
620
+ down, up = resizers
621
+
622
+ if device is None:
623
+ device = next(model.parameters()).device
624
+ assert isinstance(shape, (tuple, list))
625
+ if noise is not None:
626
+ img = noise
627
+ else:
628
+ img = th.randn(*shape, device=device)
629
+
630
+ if skip_timesteps and init_image is None:
631
+ init_image = th.zeros_like(img)
632
+ # indices = list(range(self.num_timesteps - skip_timesteps))[::-1]
633
+ indices = [120]
634
+
635
+ # scales = [2 ** i for i in range(6)]
636
+ # scales = np.repeat(scales, len(indices) // len(scales))
637
+ # scales = list(scales) + [scales[-1]] * (len(indices) - len(scales))
638
+
639
+ batch_size = shape[0]
640
+ #init_image_batch = th.tile(init_image, dims=(batch_size, 1, 1, 1))
641
+ img = self.q_sample(
642
+ x_start=init_image, #_batch,
643
+ t=th.tensor(indices[0], dtype=th.long, device=device),
644
+ noise=img,
645
+ )
646
+
647
+
648
+ #img = init_image + project_perturbation(img - init_image,
649
+ # eps=eps_project,
650
+ # p=2) # *out["sample"].abs().max(), p=2)
651
+
652
+ if progress:
653
+ # Lazy import so that we don't depend on tqdm.
654
+ from tqdm.auto import tqdm
655
+
656
+ indices = tqdm(indices)
657
+
658
+ if randomize_class and "y" in model_kwargs:
659
+ print(model.num_classes, model_kwargs["y"].shape, model_kwargs["y"].device)
660
+ model_kwargs["y"] = th.randint(
661
+ low=0,
662
+ high=model.num_classes,
663
+ size=model_kwargs["y"].shape,
664
+ device=model_kwargs["y"].device,
665
+ )
666
+ print('classes start are', model_kwargs["y"])
667
+ for i in indices:
668
+ t = th.tensor([i] * shape[0], device=device)
669
+
670
+ ############start
671
+ img = self.q_sample(
672
+ x_start=init_image,
673
+ t=th.tensor(i, dtype=th.long, device=device),
674
+ noise=noise
675
+ )
676
+ ############end
677
+
678
+
679
+ # with th.no_grad():
680
+ with th.enable_grad():
681
+ out = self.p_sample(
682
+ model,
683
+ img,
684
+ t,
685
+ clip_denoised=clip_denoised,
686
+ denoised_fn=denoised_fn,
687
+ cond_fn=cond_fn,
688
+ model_kwargs=model_kwargs,
689
+ )
690
+
691
+ #### ILVR ####
692
+ if resizers is not None and False:
693
+ if i > range_t:
694
+ print('using ILVR, changing scales', i, scales[i], ilvr_multi, out["factor_"].min())
695
+ out["sample"] = out["sample"] + ilvr_multi * out["factor_"] * (
696
+ -1 * up(scales[i])(down(scales[i])(out["sample"])) + up(scales[i])(
697
+ down(scales[i])(self.q_sample(init_image, t,
698
+ th.randn(*shape, device=device)))))
699
+
700
+
701
+ if postprocess_fn is not None:
702
+ out = postprocess_fn(out, t)
703
+ yield out, i
704
+
705
+
706
+ def tweedie(
707
+ self,
708
+ model,
709
+ shape,
710
+ model_kwargs=None,
711
+ device=None,
712
+ init_image=None,
713
+ seed=1,
714
+ indices=[120],
715
+ noise=None,
716
+ ):
717
+ th.manual_seed(seed)
718
+ random.seed(seed)
719
+ np.random.seed(seed)
720
+ batch_size = shape[0]
721
+ for i in indices:
722
+ t = th.tensor([i] * shape[0], device=device)
723
+
724
+ # p(xt|x0)
725
+ if noise is None:
726
+ noise = th.randn(*shape, device=device)
727
+ xt = self.q_sample(
728
+ x_start=init_image,
729
+ t=th.tensor(i, dtype=th.long, device=device),
730
+ noise=noise
731
+ )
732
+
733
+ # tweedie
734
+ # with th.no_grad():
735
+ with th.enable_grad():
736
+ out = self.p_mean_variance(
737
+ model,
738
+ xt,
739
+ t,
740
+ model_kwargs=model_kwargs,
741
+ )
742
+ # Save the added noise for later on
743
+ out["noise"] = noise
744
+ yield out, i
745
+
746
+ def add_noise(
747
+ self,
748
+ x0,
749
+ t,
750
+ ):
751
+ ats = self.alphas_cumprod
752
+ at = th.tensor(ats[t], dtype=th.float32)
753
+ noise = th.randn_like(x0)
754
+ xt = at.sqrt() * x0 + (1-at).sqrt() * noise
755
+ return xt
756
+
757
+ def tweedie_only(
758
+ self,
759
+ model,
760
+ xt,
761
+ t,
762
+ ):
763
+ ats = self.alphas_cumprod
764
+ at = th.tensor(ats[t], dtype=th.float32)
765
+ t_in = th.tensor(t, dtype=th.long).unsqueeze(dim=0).to(xt.device)
766
+ et = model(xt, t_in)
767
+ if et.shape[1] == 6:
768
+ et = et[:, :3]
769
+ x0t = (xt - et * (1-at).sqrt()) / at.sqrt()
770
+ return x0t
771
+
772
+ def tweedie_simple(
773
+ self,
774
+ model,
775
+ x0,
776
+ t,
777
+ ):
778
+ ats = self.alphas_cumprod
779
+ at = th.tensor(ats[t], dtype=th.float32)
780
+ # xt ~ q(xt|x0)
781
+ # torch.manual_seed(42)
782
+ noise = th.randn_like(x0)
783
+
784
+ xt = at.sqrt() * x0 + (1 - at).sqrt() * noise
785
+
786
+ # x0 = E(x0|xt)d
787
+ t_in = th.tensor(t, dtype=th.long).unsqueeze(dim=0).to(x0.device)
788
+ et = model(xt, t_in)
789
+ if et.shape[1] == 6:
790
+ et = et[:, :3]
791
+ x0t = (xt - et * (1 - at).sqrt()) / at.sqrt()
792
+ return x0t, xt
793
+
794
+
795
+ # @th.no_grad()
796
+ @th.enable_grad()
797
+ def sdedit(self, x0, t, model, eta=0.0, skip=5):
798
+ b = self.betas
799
+ n = x0.size(0)
800
+ start_t = (th.ones(n) * t).to("cuda")
801
+ at_start = compute_alpha(torch.Tensor(b), start_t.long()).to("cuda")
802
+ xt = at_start.sqrt() * x0 + (1 - at_start).sqrt() * th.randn_like(x0)
803
+
804
+ times = list(reversed(np.linspace(0, t, (t//skip)+1)))
805
+ times = list(map(int, times))
806
+
807
+ for i, t_np in tqdm(enumerate(times[:-1]), total=len(times)):
808
+ t = (th.ones(n) * times[i]).to("cuda")
809
+ next_t = (th.ones(n) * times[i+1]).to("cuda")
810
+ at = compute_alpha(b, t.long()).to("cuda")
811
+ at_next = compute_alpha(b, next_t.long()).to("cuda")
812
+
813
+ et = model(xt, t)
814
+ et = et[:, :3]
815
+
816
+ # 0. x0hat prediction
817
+ x0_t = (xt - et * (1 - at).sqrt()) / at.sqrt()
818
+ x0_t = torch.clip(x0_t, -1, 1)
819
+ # plt.imsave(f"x0t_{i:04d}.png", clear_color(x0_t))
820
+
821
+ c1 = ((1 - at / at_next) * (1 - at_next) / (1 - at)).sqrt() * eta
822
+ c2 = ((1 - at_next) - c1 ** 2).sqrt()
823
+
824
+ xt = at_next.sqrt() * x0_t + c1 * th.randn_like(x0_t) + c2 * et
825
+ # plt.imsave(f"xt_{i:04d}.png", clear_color(xt))
826
+
827
+ return xt, x0_t
828
+
829
+
830
+
831
+ def ddim_sample(
832
+ self,
833
+ model,
834
+ x,
835
+ t,
836
+ clip_denoised=True,
837
+ denoised_fn=None,
838
+ cond_fn=None,
839
+ model_kwargs=None,
840
+ eta=0.0,
841
+ ):
842
+ """
843
+ Sample x_{t-1} from the model using DDIM.
844
+
845
+ Same usage as p_sample().
846
+ """
847
+ out = self.p_mean_variance(
848
+ model,
849
+ x,
850
+ t,
851
+ clip_denoised=clip_denoised,
852
+ denoised_fn=denoised_fn,
853
+ model_kwargs=model_kwargs,
854
+ )
855
+ if cond_fn is not None:
856
+ out, factor_ = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs)
857
+
858
+ # Usually our model outputs epsilon, but we re-derive it
859
+ # in case we used x_start or x_prev prediction.
860
+ eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
861
+
862
+ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
863
+ alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)
864
+ sigma = (
865
+ eta
866
+ * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
867
+ * th.sqrt(1 - alpha_bar / alpha_bar_prev)
868
+ )
869
+ # Equation 12.
870
+ noise = th.randn_like(x)
871
+ mean_pred = (
872
+ out["pred_xstart"] * th.sqrt(alpha_bar_prev)
873
+ + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps
874
+ )
875
+ nonzero_mask = (
876
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
877
+ ) # no noise when t == 0
878
+ sample = mean_pred + nonzero_mask * sigma * noise
879
+ return {"sample": sample, "pred_xstart": out["pred_xstart"], "factor_": factor_}
880
+
881
+ def ddim_reverse_sample(
882
+ self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None, eta=0.0,
883
+ ):
884
+ """
885
+ Sample x_{t+1} from the model using DDIM reverse ODE.
886
+ """
887
+ assert eta == 0.0, "Reverse ODE only for deterministic path"
888
+ out = self.p_mean_variance(
889
+ model,
890
+ x,
891
+ t,
892
+ clip_denoised=clip_denoised,
893
+ denoised_fn=denoised_fn,
894
+ model_kwargs=model_kwargs,
895
+ )
896
+ # Usually our model outputs epsilon, but we re-derive it
897
+ # in case we used x_start or x_prev prediction.
898
+ eps = (
899
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x
900
+ - out["pred_xstart"]
901
+ ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape)
902
+ alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape)
903
+
904
+ # Equation 12. reversed
905
+ mean_pred = out["pred_xstart"] * th.sqrt(alpha_bar_next) + th.sqrt(1 - alpha_bar_next) * eps
906
+
907
+ return {"sample": mean_pred, "pred_xstart": out["pred_xstart"]}
908
+
909
+ def ddim_sample_loop(
910
+ self,
911
+ model,
912
+ shape,
913
+ noise=None,
914
+ clip_denoised=True,
915
+ denoised_fn=None,
916
+ cond_fn=None,
917
+ model_kwargs=None,
918
+ device=None,
919
+ progress=False,
920
+ eta=0.0,
921
+ skip_timesteps=0,
922
+ init_image=None,
923
+ randomize_class=False,
924
+ ):
925
+ """
926
+ Generate samples from the model using DDIM.
927
+
928
+ Same usage as p_sample_loop().
929
+ """
930
+ final = None
931
+ for sample in self.ddim_sample_loop_progressive(
932
+ model,
933
+ shape,
934
+ noise=noise,
935
+ clip_denoised=clip_denoised,
936
+ denoised_fn=denoised_fn,
937
+ cond_fn=cond_fn,
938
+ model_kwargs=model_kwargs,
939
+ device=device,
940
+ progress=progress,
941
+ eta=eta,
942
+ skip_timesteps=skip_timesteps,
943
+ init_image=init_image,
944
+ randomize_class=randomize_class,
945
+ ):
946
+ final = sample
947
+ return final["sample"]
948
+
949
+ def ddim_sample_loop_progressive(
950
+ self,
951
+ model,
952
+ shape,
953
+ noise=None,
954
+ clip_denoised=True,
955
+ denoised_fn=None,
956
+ cond_fn=None,
957
+ model_kwargs=None,
958
+ device=None,
959
+ progress=False,
960
+ eta=0.0,
961
+ skip_timesteps=0,
962
+ init_image=None,
963
+ randomize_class=False,
964
+ resizers=None,
965
+ range_t=0,
966
+ postprocess_fn=None,
967
+ eps_project=30,
968
+ ilvr_multi=0
969
+
970
+ ):
971
+ """
972
+ Use DDIM to sample from the model and yield intermediate samples from
973
+ each timestep of DDIM.
974
+
975
+ Same usage as p_sample_loop_progressive().
976
+ """
977
+ if device is None:
978
+ device = next(model.parameters()).device
979
+ assert isinstance(shape, (tuple, list))
980
+ if noise is not None:
981
+ img = noise
982
+ else:
983
+ img = th.randn(*shape, device=device)
984
+
985
+ if resizers is not None:
986
+ down, up = resizers
987
+ batch_size = shape[0]
988
+ #indices = list(range(self.num_timesteps))[::-1]
989
+ indices = list(range(self.num_timesteps - skip_timesteps))[::-1]
990
+
991
+ scales = [2**i for i in range(6)]
992
+ scales = np.repeat(scales, len(indices) // len(scales))
993
+ scales = list(scales) + [scales[-1]] * (len(indices) - len(scales))
994
+
995
+ #init_image_batch = th.tile(init_image, dims=(batch_size, 1, 1, 1))
996
+ img = self.q_sample(
997
+ x_start=init_image,
998
+ t=th.tensor(indices[0], dtype=th.long, device=device),
999
+ noise=img,
1000
+ )
1001
+
1002
+ #print('projecting first image', eps_project)
1003
+ #img = init_image + project_perturbation(img - init_image, p=2, eps=eps_project)
1004
+ #img = init_image
1005
+ #print('sampling latents', indices)
1006
+ #for i in indices:
1007
+ # t = th.tensor([i] * shape[0], device=device)
1008
+ #
1009
+ # img = self.ddim_reverse_sample(
1010
+ # model=model,
1011
+ # x=img,
1012
+ # t=t
1013
+ # )["sample"].detach()
1014
+
1015
+ #indices = list(range(self.num_timesteps))[::-1]
1016
+ if progress:
1017
+ # Lazy import so that we don't depend on tqdm.
1018
+ from tqdm.auto import tqdm
1019
+
1020
+ indices = tqdm(indices)
1021
+
1022
+ for i in indices:
1023
+ t = th.tensor([i] * shape[0], device=device)
1024
+ if randomize_class and "y" in model_kwargs:
1025
+ model_kwargs["y"] = th.randint(
1026
+ low=0,
1027
+ high=model.num_classes,
1028
+ size=model_kwargs["y"].shape,
1029
+ device=model_kwargs["y"].device,
1030
+ )
1031
+ # with th.no_grad():
1032
+ with th.enable_grad():
1033
+ out = self.ddim_sample(
1034
+ model,
1035
+ img,
1036
+ t,
1037
+ clip_denoised=clip_denoised,
1038
+ denoised_fn=denoised_fn,
1039
+ cond_fn=cond_fn,
1040
+ model_kwargs=model_kwargs,
1041
+ eta=eta,
1042
+ )
1043
+ yield out
1044
+
1045
+ #### ILVR ####
1046
+ if resizers is not None and False:
1047
+ if i > range_t:
1048
+ print('using ILVR, changing scales', i, scales[i], ilvr_multi, out["factor_"].min())
1049
+ out["sample"] = out["sample"] + ilvr_multi*out["factor_"]*(-1 * up(scales[i])(down(scales[i])(out["sample"])) + up(scales[i])(
1050
+ down(scales[i])(self.q_sample(init_image, t,
1051
+ th.randn(*shape, device=device)))))
1052
+
1053
+ if postprocess_fn is not None:
1054
+ out = postprocess_fn(out, t)
1055
+
1056
+ img = out["sample"]
1057
+
1058
+ def _vb_terms_bpd(self, model, x_start, x_t, t, clip_denoised=True, model_kwargs=None):
1059
+ """
1060
+ Get a term for the variational lower-bound.
1061
+
1062
+ The resulting units are bits (rather than nats, as one might expect).
1063
+ This allows for comparison to other papers.
1064
+
1065
+ :return: a dict with the following keys:
1066
+ - 'output': a shape [N] tensor of NLLs or KLs.
1067
+ - 'pred_xstart': the x_0 predictions.
1068
+ """
1069
+ true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance(
1070
+ x_start=x_start, x_t=x_t, t=t
1071
+ )
1072
+ out = self.p_mean_variance(
1073
+ model, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs
1074
+ )
1075
+ kl = normal_kl(true_mean, true_log_variance_clipped, out["mean"], out["log_variance"])
1076
+ kl = mean_flat(kl) / np.log(2.0)
1077
+
1078
+ decoder_nll = -discretized_gaussian_log_likelihood(
1079
+ x_start, means=out["mean"], log_scales=0.5 * out["log_variance"]
1080
+ )
1081
+ assert decoder_nll.shape == x_start.shape
1082
+ decoder_nll = mean_flat(decoder_nll) / np.log(2.0)
1083
+
1084
+ # At the first timestep return the decoder NLL,
1085
+ # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))
1086
+ output = th.where((t == 0), decoder_nll, kl)
1087
+ return {"output": output, "pred_xstart": out["pred_xstart"]}
1088
+
1089
+ def training_losses(self, model, x_start, t, model_kwargs=None, noise=None):
1090
+ """
1091
+ Compute training losses for a single timestep.
1092
+
1093
+ :param model: the model to evaluate loss on.
1094
+ :param x_start: the [N x C x ...] tensor of inputs.
1095
+ :param t: a batch of timestep indices.
1096
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
1097
+ pass to the model. This can be used for conditioning.
1098
+ :param noise: if specified, the specific Gaussian noise to try to remove.
1099
+ :return: a dict with the key "loss" containing a tensor of shape [N].
1100
+ Some mean or variance settings may also have other keys.
1101
+ """
1102
+ if model_kwargs is None:
1103
+ model_kwargs = {}
1104
+ if noise is None:
1105
+ noise = th.randn_like(x_start)
1106
+ x_t = self.q_sample(x_start, t, noise=noise)
1107
+
1108
+ terms = {}
1109
+
1110
+ if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL:
1111
+ terms["loss"] = self._vb_terms_bpd(
1112
+ model=model,
1113
+ x_start=x_start,
1114
+ x_t=x_t,
1115
+ t=t,
1116
+ clip_denoised=False,
1117
+ model_kwargs=model_kwargs,
1118
+ )["output"]
1119
+ if self.loss_type == LossType.RESCALED_KL:
1120
+ terms["loss"] *= self.num_timesteps
1121
+ elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE:
1122
+ model_output = model(x_t, self._scale_timesteps(t), **model_kwargs)
1123
+
1124
+ if self.model_var_type in [
1125
+ ModelVarType.LEARNED,
1126
+ ModelVarType.LEARNED_RANGE,
1127
+ ]:
1128
+ B, C = x_t.shape[:2]
1129
+ assert model_output.shape == (B, C * 2, *x_t.shape[2:])
1130
+ model_output, model_var_values = th.split(model_output, C, dim=1)
1131
+ # Learn the variance using the variational bound, but don't let
1132
+ # it affect our mean prediction.
1133
+ frozen_out = th.cat([model_output.detach(), model_var_values], dim=1)
1134
+ terms["vb"] = self._vb_terms_bpd(
1135
+ model=lambda *args, r=frozen_out: r,
1136
+ x_start=x_start,
1137
+ x_t=x_t,
1138
+ t=t,
1139
+ clip_denoised=False,
1140
+ )["output"]
1141
+ if self.loss_type == LossType.RESCALED_MSE:
1142
+ # Divide by 1000 for equivalence with initial implementation.
1143
+ # Without a factor of 1/1000, the VB term hurts the MSE term.
1144
+ terms["vb"] *= self.num_timesteps / 1000.0
1145
+
1146
+ target = {
1147
+ ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance(
1148
+ x_start=x_start, x_t=x_t, t=t
1149
+ )[0],
1150
+ ModelMeanType.START_X: x_start,
1151
+ ModelMeanType.EPSILON: noise,
1152
+ }[self.model_mean_type]
1153
+ assert model_output.shape == target.shape == x_start.shape
1154
+ terms["mse"] = mean_flat((target - model_output) ** 2)
1155
+ if "vb" in terms:
1156
+ terms["loss"] = terms["mse"] + terms["vb"]
1157
+ else:
1158
+ terms["loss"] = terms["mse"]
1159
+ else:
1160
+ raise NotImplementedError(self.loss_type)
1161
+
1162
+ return terms
1163
+
1164
+ def _prior_bpd(self, x_start):
1165
+ """
1166
+ Get the prior KL term for the variational lower-bound, measured in
1167
+ bits-per-dim.
1168
+
1169
+ This term can't be optimized, as it only depends on the encoder.
1170
+
1171
+ :param x_start: the [N x C x ...] tensor of inputs.
1172
+ :return: a batch of [N] KL values (in bits), one per batch element.
1173
+ """
1174
+ batch_size = x_start.shape[0]
1175
+ t = th.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
1176
+ qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
1177
+ kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
1178
+ return mean_flat(kl_prior) / np.log(2.0)
1179
+
1180
+ def calc_bpd_loop(self, model, x_start, clip_denoised=True, model_kwargs=None):
1181
+ """
1182
+ Compute the entire variational lower-bound, measured in bits-per-dim,
1183
+ as well as other related quantities.
1184
+
1185
+ :param model: the model to evaluate loss on.
1186
+ :param x_start: the [N x C x ...] tensor of inputs.
1187
+ :param clip_denoised: if True, clip denoised samples.
1188
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
1189
+ pass to the model. This can be used for conditioning.
1190
+
1191
+ :return: a dict containing the following keys:
1192
+ - total_bpd: the total variational lower-bound, per batch element.
1193
+ - prior_bpd: the prior term in the lower-bound.
1194
+ - vb: an [N x T] tensor of terms in the lower-bound.
1195
+ - xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep.
1196
+ - mse: an [N x T] tensor of epsilon MSEs for each timestep.
1197
+ """
1198
+ device = x_start.device
1199
+ batch_size = x_start.shape[0]
1200
+
1201
+ vb = []
1202
+ xstart_mse = []
1203
+ mse = []
1204
+ for t in list(range(self.num_timesteps))[::-1]:
1205
+ t_batch = th.tensor([t] * batch_size, device=device)
1206
+ noise = th.randn_like(x_start)
1207
+ x_t = self.q_sample(x_start=x_start, t=t_batch, noise=noise)
1208
+ # Calculate VLB term at the current timestep
1209
+ # with th.no_grad():
1210
+ with th.enable_grad():
1211
+ out = self._vb_terms_bpd(
1212
+ model,
1213
+ x_start=x_start,
1214
+ x_t=x_t,
1215
+ t=t_batch,
1216
+ clip_denoised=clip_denoised,
1217
+ model_kwargs=model_kwargs,
1218
+ )
1219
+ vb.append(out["output"])
1220
+ xstart_mse.append(mean_flat((out["pred_xstart"] - x_start) ** 2))
1221
+ eps = self._predict_eps_from_xstart(x_t, t_batch, out["pred_xstart"])
1222
+ mse.append(mean_flat((eps - noise) ** 2))
1223
+
1224
+ vb = th.stack(vb, dim=1)
1225
+ xstart_mse = th.stack(xstart_mse, dim=1)
1226
+ mse = th.stack(mse, dim=1)
1227
+
1228
+ prior_bpd = self._prior_bpd(x_start)
1229
+ total_bpd = vb.sum(dim=1) + prior_bpd
1230
+ return {
1231
+ "total_bpd": total_bpd,
1232
+ "prior_bpd": prior_bpd,
1233
+ "vb": vb,
1234
+ "xstart_mse": xstart_mse,
1235
+ "mse": mse,
1236
+ }
1237
+
1238
+
1239
+ def _extract_into_tensor(arr, timesteps, broadcast_shape):
1240
+ """
1241
+ Extract values from a 1-D numpy array for a batch of indices.
1242
+
1243
+ :param arr: the 1-D numpy array.
1244
+ :param timesteps: a tensor of indices into the array to extract.
1245
+ :param broadcast_shape: a larger shape of K dimensions with the batch
1246
+ dimension equal to the length of timesteps.
1247
+ :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims.
1248
+ """
1249
+ res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float()
1250
+ while len(res.shape) < len(broadcast_shape):
1251
+ res = res[..., None]
1252
+ return res.expand(broadcast_shape)
guided_diffusion/guided_diffusion/image_datasets.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+
4
+ from PIL import Image
5
+ import blobfile as bf
6
+ from mpi4py import MPI
7
+ import numpy as np
8
+ from torch.utils.data import DataLoader, Dataset
9
+
10
+
11
+ def load_data(
12
+ *,
13
+ data_dir,
14
+ batch_size,
15
+ image_size,
16
+ class_cond=False,
17
+ deterministic=False,
18
+ random_crop=False,
19
+ random_flip=True,
20
+ ):
21
+ """
22
+ For a dataset, create a generator over (images, kwargs) pairs.
23
+
24
+ Each images is an NCHW float tensor, and the kwargs dict contains zero or
25
+ more keys, each of which map to a batched Tensor of their own.
26
+ The kwargs dict can be used for class labels, in which case the key is "y"
27
+ and the values are integer tensors of class labels.
28
+
29
+ :param data_dir: a dataset directory.
30
+ :param batch_size: the batch size of each returned pair.
31
+ :param image_size: the size to which images are resized.
32
+ :param class_cond: if True, include a "y" key in returned dicts for class
33
+ label. If classes are not available and this is true, an
34
+ exception will be raised.
35
+ :param deterministic: if True, yield results in a deterministic order.
36
+ :param random_crop: if True, randomly crop the images for augmentation.
37
+ :param random_flip: if True, randomly flip the images for augmentation.
38
+ """
39
+ if not data_dir:
40
+ raise ValueError("unspecified data directory")
41
+ all_files = _list_image_files_recursively(data_dir)
42
+ classes = None
43
+ if class_cond:
44
+ # Assume classes are the first part of the filename,
45
+ # before an underscore.
46
+ class_names = [bf.basename(path).split("_")[0] for path in all_files]
47
+ sorted_classes = {x: i for i, x in enumerate(sorted(set(class_names)))}
48
+ classes = [sorted_classes[x] for x in class_names]
49
+ dataset = ImageDataset(
50
+ image_size,
51
+ all_files,
52
+ classes=classes,
53
+ shard=MPI.COMM_WORLD.Get_rank(),
54
+ num_shards=MPI.COMM_WORLD.Get_size(),
55
+ random_crop=random_crop,
56
+ random_flip=random_flip,
57
+ )
58
+ if deterministic:
59
+ loader = DataLoader(
60
+ dataset, batch_size=batch_size, shuffle=False, num_workers=1, drop_last=True
61
+ )
62
+ else:
63
+ loader = DataLoader(
64
+ dataset, batch_size=batch_size, shuffle=True, num_workers=1, drop_last=True
65
+ )
66
+ while True:
67
+ yield from loader
68
+
69
+
70
+ def _list_image_files_recursively(data_dir):
71
+ results = []
72
+ for entry in sorted(bf.listdir(data_dir)):
73
+ full_path = bf.join(data_dir, entry)
74
+ ext = entry.split(".")[-1]
75
+ if "." in entry and ext.lower() in ["jpg", "jpeg", "png", "gif"]:
76
+ results.append(full_path)
77
+ elif bf.isdir(full_path):
78
+ results.extend(_list_image_files_recursively(full_path))
79
+ return results
80
+
81
+
82
+ class ImageDataset(Dataset):
83
+ def __init__(
84
+ self,
85
+ resolution,
86
+ image_paths,
87
+ classes=None,
88
+ shard=0,
89
+ num_shards=1,
90
+ random_crop=False,
91
+ random_flip=True,
92
+ ):
93
+ super().__init__()
94
+ self.resolution = resolution
95
+ self.local_images = image_paths[shard:][::num_shards]
96
+ self.local_classes = None if classes is None else classes[shard:][::num_shards]
97
+ self.random_crop = random_crop
98
+ self.random_flip = random_flip
99
+
100
+ def __len__(self):
101
+ return len(self.local_images)
102
+
103
+ def __getitem__(self, idx):
104
+ path = self.local_images[idx]
105
+ with bf.BlobFile(path, "rb") as f:
106
+ pil_image = Image.open(f)
107
+ pil_image.load()
108
+ pil_image = pil_image.convert("RGB")
109
+
110
+ if self.random_crop:
111
+ arr = random_crop_arr(pil_image, self.resolution)
112
+ else:
113
+ arr = center_crop_arr(pil_image, self.resolution)
114
+
115
+ if self.random_flip and random.random() < 0.5:
116
+ arr = arr[:, ::-1]
117
+
118
+ arr = arr.astype(np.float32) / 127.5 - 1
119
+
120
+ out_dict = {}
121
+ if self.local_classes is not None:
122
+ out_dict["y"] = np.array(self.local_classes[idx], dtype=np.int64)
123
+ return np.transpose(arr, [2, 0, 1]), out_dict
124
+
125
+
126
+ def center_crop_arr(pil_image, image_size):
127
+ # We are not on a new enough PIL to support the `reducing_gap`
128
+ # argument, which uses BOX downsampling at powers of two first.
129
+ # Thus, we do it by hand to improve downsample quality.
130
+ while min(*pil_image.size) >= 2 * image_size:
131
+ pil_image = pil_image.resize(
132
+ tuple(x // 2 for x in pil_image.size), resample=Image.BOX
133
+ )
134
+
135
+ scale = image_size / min(*pil_image.size)
136
+ pil_image = pil_image.resize(
137
+ tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC
138
+ )
139
+
140
+ arr = np.array(pil_image)
141
+ crop_y = (arr.shape[0] - image_size) // 2
142
+ crop_x = (arr.shape[1] - image_size) // 2
143
+ return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size]
144
+
145
+
146
+ def random_crop_arr(pil_image, image_size, min_crop_frac=0.8, max_crop_frac=1.0):
147
+ min_smaller_dim_size = math.ceil(image_size / max_crop_frac)
148
+ max_smaller_dim_size = math.ceil(image_size / min_crop_frac)
149
+ smaller_dim_size = random.randrange(min_smaller_dim_size, max_smaller_dim_size + 1)
150
+
151
+ # We are not on a new enough PIL to support the `reducing_gap`
152
+ # argument, which uses BOX downsampling at powers of two first.
153
+ # Thus, we do it by hand to improve downsample quality.
154
+ while min(*pil_image.size) >= 2 * smaller_dim_size:
155
+ pil_image = pil_image.resize(
156
+ tuple(x // 2 for x in pil_image.size), resample=Image.BOX
157
+ )
158
+
159
+ scale = smaller_dim_size / min(*pil_image.size)
160
+ pil_image = pil_image.resize(
161
+ tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC
162
+ )
163
+
164
+ arr = np.array(pil_image)
165
+ crop_y = random.randrange(arr.shape[0] - image_size + 1)
166
+ crop_x = random.randrange(arr.shape[1] - image_size + 1)
167
+ return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size]
guided_diffusion/guided_diffusion/logger.py ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Logger copied from OpenAI baselines to avoid extra RL-based dependencies:
3
+ https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/logger.py
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ import shutil
9
+ import os.path as osp
10
+ import json
11
+ import time
12
+ import datetime
13
+ import tempfile
14
+ import warnings
15
+ from collections import defaultdict
16
+ from contextlib import contextmanager
17
+
18
+ DEBUG = 10
19
+ INFO = 20
20
+ WARN = 30
21
+ ERROR = 40
22
+
23
+ DISABLED = 50
24
+
25
+
26
+ class KVWriter(object):
27
+ def writekvs(self, kvs):
28
+ raise NotImplementedError
29
+
30
+
31
+ class SeqWriter(object):
32
+ def writeseq(self, seq):
33
+ raise NotImplementedError
34
+
35
+
36
+ class HumanOutputFormat(KVWriter, SeqWriter):
37
+ def __init__(self, filename_or_file):
38
+ if isinstance(filename_or_file, str):
39
+ self.file = open(filename_or_file, "wt")
40
+ self.own_file = True
41
+ else:
42
+ assert hasattr(filename_or_file, "read"), (
43
+ "expected file or str, got %s" % filename_or_file
44
+ )
45
+ self.file = filename_or_file
46
+ self.own_file = False
47
+
48
+ def writekvs(self, kvs):
49
+ # Create strings for printing
50
+ key2str = {}
51
+ for (key, val) in sorted(kvs.items()):
52
+ if hasattr(val, "__float__"):
53
+ valstr = "%-8.3g" % val
54
+ else:
55
+ valstr = str(val)
56
+ key2str[self._truncate(key)] = self._truncate(valstr)
57
+
58
+ # Find max widths
59
+ if len(key2str) == 0:
60
+ print("WARNING: tried to write empty key-value dict")
61
+ return
62
+ else:
63
+ keywidth = max(map(len, key2str.keys()))
64
+ valwidth = max(map(len, key2str.values()))
65
+
66
+ # Write out the data
67
+ dashes = "-" * (keywidth + valwidth + 7)
68
+ lines = [dashes]
69
+ for (key, val) in sorted(key2str.items(), key=lambda kv: kv[0].lower()):
70
+ lines.append(
71
+ "| %s%s | %s%s |"
72
+ % (key, " " * (keywidth - len(key)), val, " " * (valwidth - len(val)))
73
+ )
74
+ lines.append(dashes)
75
+ self.file.write("\n".join(lines) + "\n")
76
+
77
+ # Flush the output to the file
78
+ self.file.flush()
79
+
80
+ def _truncate(self, s):
81
+ maxlen = 30
82
+ return s[: maxlen - 3] + "..." if len(s) > maxlen else s
83
+
84
+ def writeseq(self, seq):
85
+ seq = list(seq)
86
+ for (i, elem) in enumerate(seq):
87
+ self.file.write(elem)
88
+ if i < len(seq) - 1: # add space unless this is the last one
89
+ self.file.write(" ")
90
+ self.file.write("\n")
91
+ self.file.flush()
92
+
93
+ def close(self):
94
+ if self.own_file:
95
+ self.file.close()
96
+
97
+
98
+ class JSONOutputFormat(KVWriter):
99
+ def __init__(self, filename):
100
+ self.file = open(filename, "wt")
101
+
102
+ def writekvs(self, kvs):
103
+ for k, v in sorted(kvs.items()):
104
+ if hasattr(v, "dtype"):
105
+ kvs[k] = float(v)
106
+ self.file.write(json.dumps(kvs) + "\n")
107
+ self.file.flush()
108
+
109
+ def close(self):
110
+ self.file.close()
111
+
112
+
113
+ class CSVOutputFormat(KVWriter):
114
+ def __init__(self, filename):
115
+ self.file = open(filename, "w+t")
116
+ self.keys = []
117
+ self.sep = ","
118
+
119
+ def writekvs(self, kvs):
120
+ # Add our current row to the history
121
+ extra_keys = list(kvs.keys() - self.keys)
122
+ extra_keys.sort()
123
+ if extra_keys:
124
+ self.keys.extend(extra_keys)
125
+ self.file.seek(0)
126
+ lines = self.file.readlines()
127
+ self.file.seek(0)
128
+ for (i, k) in enumerate(self.keys):
129
+ if i > 0:
130
+ self.file.write(",")
131
+ self.file.write(k)
132
+ self.file.write("\n")
133
+ for line in lines[1:]:
134
+ self.file.write(line[:-1])
135
+ self.file.write(self.sep * len(extra_keys))
136
+ self.file.write("\n")
137
+ for (i, k) in enumerate(self.keys):
138
+ if i > 0:
139
+ self.file.write(",")
140
+ v = kvs.get(k)
141
+ if v is not None:
142
+ self.file.write(str(v))
143
+ self.file.write("\n")
144
+ self.file.flush()
145
+
146
+ def close(self):
147
+ self.file.close()
148
+
149
+
150
+ class TensorBoardOutputFormat(KVWriter):
151
+ """
152
+ Dumps key/value pairs into TensorBoard's numeric format.
153
+ """
154
+
155
+ def __init__(self, dir):
156
+ os.makedirs(dir, exist_ok=True)
157
+ self.dir = dir
158
+ self.step = 1
159
+ prefix = "events"
160
+ path = osp.join(osp.abspath(dir), prefix)
161
+ import tensorflow as tf
162
+ from tensorflow.python import pywrap_tensorflow
163
+ from tensorflow.core.util import event_pb2
164
+ from tensorflow.python.util import compat
165
+
166
+ self.tf = tf
167
+ self.event_pb2 = event_pb2
168
+ self.pywrap_tensorflow = pywrap_tensorflow
169
+ self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path))
170
+
171
+ def writekvs(self, kvs):
172
+ def summary_val(k, v):
173
+ kwargs = {"tag": k, "simple_value": float(v)}
174
+ return self.tf.Summary.Value(**kwargs)
175
+
176
+ summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()])
177
+ event = self.event_pb2.Event(wall_time=time.time(), summary=summary)
178
+ event.step = (
179
+ self.step
180
+ ) # is there any reason why you'd want to specify the step?
181
+ self.writer.WriteEvent(event)
182
+ self.writer.Flush()
183
+ self.step += 1
184
+
185
+ def close(self):
186
+ if self.writer:
187
+ self.writer.Close()
188
+ self.writer = None
189
+
190
+
191
+ def make_output_format(format, ev_dir, log_suffix=""):
192
+ os.makedirs(ev_dir, exist_ok=True)
193
+ if format == "stdout":
194
+ return HumanOutputFormat(sys.stdout)
195
+ elif format == "log":
196
+ return HumanOutputFormat(osp.join(ev_dir, "log%s.txt" % log_suffix))
197
+ elif format == "json":
198
+ return JSONOutputFormat(osp.join(ev_dir, "progress%s.json" % log_suffix))
199
+ elif format == "csv":
200
+ return CSVOutputFormat(osp.join(ev_dir, "progress%s.csv" % log_suffix))
201
+ elif format == "tensorboard":
202
+ return TensorBoardOutputFormat(osp.join(ev_dir, "tb%s" % log_suffix))
203
+ else:
204
+ raise ValueError("Unknown format specified: %s" % (format,))
205
+
206
+
207
+ # ================================================================
208
+ # API
209
+ # ================================================================
210
+
211
+
212
+ def logkv(key, val):
213
+ """
214
+ Log a value of some diagnostic
215
+ Call this once for each diagnostic quantity, each iteration
216
+ If called many times, last value will be used.
217
+ """
218
+ get_current().logkv(key, val)
219
+
220
+
221
+ def logkv_mean(key, val):
222
+ """
223
+ The same as logkv(), but if called many times, values averaged.
224
+ """
225
+ get_current().logkv_mean(key, val)
226
+
227
+
228
+ def logkvs(d):
229
+ """
230
+ Log a dictionary of key-value pairs
231
+ """
232
+ for (k, v) in d.items():
233
+ logkv(k, v)
234
+
235
+
236
+ def dumpkvs():
237
+ """
238
+ Write all of the diagnostics from the current iteration
239
+ """
240
+ return get_current().dumpkvs()
241
+
242
+
243
+ def getkvs():
244
+ return get_current().name2val
245
+
246
+
247
+ def log(*args, level=INFO):
248
+ """
249
+ Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).
250
+ """
251
+ get_current().log(*args, level=level)
252
+
253
+
254
+ def debug(*args):
255
+ log(*args, level=DEBUG)
256
+
257
+
258
+ def info(*args):
259
+ log(*args, level=INFO)
260
+
261
+
262
+ def warn(*args):
263
+ log(*args, level=WARN)
264
+
265
+
266
+ def error(*args):
267
+ log(*args, level=ERROR)
268
+
269
+
270
+ def set_level(level):
271
+ """
272
+ Set logging threshold on current logger.
273
+ """
274
+ get_current().set_level(level)
275
+
276
+
277
+ def set_comm(comm):
278
+ get_current().set_comm(comm)
279
+
280
+
281
+ def get_dir():
282
+ """
283
+ Get directory that log files are being written to.
284
+ will be None if there is no output directory (i.e., if you didn't call start)
285
+ """
286
+ return get_current().get_dir()
287
+
288
+
289
+ record_tabular = logkv
290
+ dump_tabular = dumpkvs
291
+
292
+
293
+ @contextmanager
294
+ def profile_kv(scopename):
295
+ logkey = "wait_" + scopename
296
+ tstart = time.time()
297
+ try:
298
+ yield
299
+ finally:
300
+ get_current().name2val[logkey] += time.time() - tstart
301
+
302
+
303
+ def profile(n):
304
+ """
305
+ Usage:
306
+ @profile("my_func")
307
+ def my_func(): code
308
+ """
309
+
310
+ def decorator_with_name(func):
311
+ def func_wrapper(*args, **kwargs):
312
+ with profile_kv(n):
313
+ return func(*args, **kwargs)
314
+
315
+ return func_wrapper
316
+
317
+ return decorator_with_name
318
+
319
+
320
+ # ================================================================
321
+ # Backend
322
+ # ================================================================
323
+
324
+
325
+ def get_current():
326
+ if Logger.CURRENT is None:
327
+ _configure_default_logger()
328
+
329
+ return Logger.CURRENT
330
+
331
+
332
+ class Logger(object):
333
+ DEFAULT = None # A logger with no output files. (See right below class definition)
334
+ # So that you can still log to the terminal without setting up any output files
335
+ CURRENT = None # Current logger being used by the free functions above
336
+
337
+ def __init__(self, dir, output_formats, comm=None):
338
+ self.name2val = defaultdict(float) # values this iteration
339
+ self.name2cnt = defaultdict(int)
340
+ self.level = INFO
341
+ self.dir = dir
342
+ self.output_formats = output_formats
343
+ self.comm = comm
344
+
345
+ # Logging API, forwarded
346
+ # ----------------------------------------
347
+ def logkv(self, key, val):
348
+ self.name2val[key] = val
349
+
350
+ def logkv_mean(self, key, val):
351
+ oldval, cnt = self.name2val[key], self.name2cnt[key]
352
+ self.name2val[key] = oldval * cnt / (cnt + 1) + val / (cnt + 1)
353
+ self.name2cnt[key] = cnt + 1
354
+
355
+ def dumpkvs(self):
356
+ if self.comm is None:
357
+ d = self.name2val
358
+ else:
359
+ d = mpi_weighted_mean(
360
+ self.comm,
361
+ {
362
+ name: (val, self.name2cnt.get(name, 1))
363
+ for (name, val) in self.name2val.items()
364
+ },
365
+ )
366
+ if self.comm.rank != 0:
367
+ d["dummy"] = 1 # so we don't get a warning about empty dict
368
+ out = d.copy() # Return the dict for unit testing purposes
369
+ for fmt in self.output_formats:
370
+ if isinstance(fmt, KVWriter):
371
+ fmt.writekvs(d)
372
+ self.name2val.clear()
373
+ self.name2cnt.clear()
374
+ return out
375
+
376
+ def log(self, *args, level=INFO):
377
+ if self.level <= level:
378
+ self._do_log(args)
379
+
380
+ # Configuration
381
+ # ----------------------------------------
382
+ def set_level(self, level):
383
+ self.level = level
384
+
385
+ def set_comm(self, comm):
386
+ self.comm = comm
387
+
388
+ def get_dir(self):
389
+ return self.dir
390
+
391
+ def close(self):
392
+ for fmt in self.output_formats:
393
+ fmt.close()
394
+
395
+ # Misc
396
+ # ----------------------------------------
397
+ def _do_log(self, args):
398
+ for fmt in self.output_formats:
399
+ if isinstance(fmt, SeqWriter):
400
+ fmt.writeseq(map(str, args))
401
+
402
+
403
+ def get_rank_without_mpi_import():
404
+ # check environment variables here instead of importing mpi4py
405
+ # to avoid calling MPI_Init() when this module is imported
406
+ for varname in ["PMI_RANK", "OMPI_COMM_WORLD_RANK"]:
407
+ if varname in os.environ:
408
+ return int(os.environ[varname])
409
+ return 0
410
+
411
+
412
+ def mpi_weighted_mean(comm, local_name2valcount):
413
+ """
414
+ Copied from: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/common/mpi_util.py#L110
415
+ Perform a weighted average over dicts that are each on a different node
416
+ Input: local_name2valcount: dict mapping key -> (value, count)
417
+ Returns: key -> mean
418
+ """
419
+ all_name2valcount = comm.gather(local_name2valcount)
420
+ if comm.rank == 0:
421
+ name2sum = defaultdict(float)
422
+ name2count = defaultdict(float)
423
+ for n2vc in all_name2valcount:
424
+ for (name, (val, count)) in n2vc.items():
425
+ try:
426
+ val = float(val)
427
+ except ValueError:
428
+ if comm.rank == 0:
429
+ warnings.warn(
430
+ "WARNING: tried to compute mean on non-float {}={}".format(
431
+ name, val
432
+ )
433
+ )
434
+ else:
435
+ name2sum[name] += val * count
436
+ name2count[name] += count
437
+ return {name: name2sum[name] / name2count[name] for name in name2sum}
438
+ else:
439
+ return {}
440
+
441
+
442
+ def configure(dir=None, format_strs=None, comm=None, log_suffix=""):
443
+ """
444
+ If comm is provided, average all numerical stats across that comm
445
+ """
446
+ if dir is None:
447
+ dir = os.getenv("OPENAI_LOGDIR")
448
+ if dir is None:
449
+ dir = osp.join(
450
+ tempfile.gettempdir(),
451
+ datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"),
452
+ )
453
+ assert isinstance(dir, str)
454
+ dir = os.path.expanduser(dir)
455
+ os.makedirs(os.path.expanduser(dir), exist_ok=True)
456
+
457
+ rank = get_rank_without_mpi_import()
458
+ if rank > 0:
459
+ log_suffix = log_suffix + "-rank%03i" % rank
460
+
461
+ if format_strs is None:
462
+ if rank == 0:
463
+ format_strs = os.getenv("OPENAI_LOG_FORMAT", "stdout,log,csv").split(",")
464
+ else:
465
+ format_strs = os.getenv("OPENAI_LOG_FORMAT_MPI", "log").split(",")
466
+ format_strs = filter(None, format_strs)
467
+ output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs]
468
+
469
+ Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm)
470
+ if output_formats:
471
+ log("Logging to %s" % dir)
472
+
473
+
474
+ def _configure_default_logger():
475
+ configure()
476
+ Logger.DEFAULT = Logger.CURRENT
477
+
478
+
479
+ def reset():
480
+ if Logger.CURRENT is not Logger.DEFAULT:
481
+ Logger.CURRENT.close()
482
+ Logger.CURRENT = Logger.DEFAULT
483
+ log("Reset logger")
484
+
485
+
486
+ @contextmanager
487
+ def scoped_configure(dir=None, format_strs=None, comm=None):
488
+ prevlogger = Logger.CURRENT
489
+ configure(dir=dir, format_strs=format_strs, comm=comm)
490
+ try:
491
+ yield
492
+ finally:
493
+ Logger.CURRENT.close()
494
+ Logger.CURRENT = prevlogger
495
+
guided_diffusion/guided_diffusion/losses.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helpers for various likelihood-based losses. These are ported from the original
3
+ Ho et al. diffusion models codebase:
4
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/utils.py
5
+ """
6
+
7
+ import numpy as np
8
+
9
+ import torch as th
10
+
11
+
12
+ def normal_kl(mean1, logvar1, mean2, logvar2):
13
+ """
14
+ Compute the KL divergence between two gaussians.
15
+
16
+ Shapes are automatically broadcasted, so batches can be compared to
17
+ scalars, among other use cases.
18
+ """
19
+ tensor = None
20
+ for obj in (mean1, logvar1, mean2, logvar2):
21
+ if isinstance(obj, th.Tensor):
22
+ tensor = obj
23
+ break
24
+ assert tensor is not None, "at least one argument must be a Tensor"
25
+
26
+ # Force variances to be Tensors. Broadcasting helps convert scalars to
27
+ # Tensors, but it does not work for th.exp().
28
+ logvar1, logvar2 = [
29
+ x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor)
30
+ for x in (logvar1, logvar2)
31
+ ]
32
+
33
+ return 0.5 * (
34
+ -1.0
35
+ + logvar2
36
+ - logvar1
37
+ + th.exp(logvar1 - logvar2)
38
+ + ((mean1 - mean2) ** 2) * th.exp(-logvar2)
39
+ )
40
+
41
+
42
+ def approx_standard_normal_cdf(x):
43
+ """
44
+ A fast approximation of the cumulative distribution function of the
45
+ standard normal.
46
+ """
47
+ return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3))))
48
+
49
+
50
+ def discretized_gaussian_log_likelihood(x, *, means, log_scales):
51
+ """
52
+ Compute the log-likelihood of a Gaussian distribution discretizing to a
53
+ given image.
54
+
55
+ :param x: the target images. It is assumed that this was uint8 values,
56
+ rescaled to the range [-1, 1].
57
+ :param means: the Gaussian mean Tensor.
58
+ :param log_scales: the Gaussian log stddev Tensor.
59
+ :return: a tensor like x of log probabilities (in nats).
60
+ """
61
+ assert x.shape == means.shape == log_scales.shape
62
+ centered_x = x - means
63
+ inv_stdv = th.exp(-log_scales)
64
+ plus_in = inv_stdv * (centered_x + 1.0 / 255.0)
65
+ cdf_plus = approx_standard_normal_cdf(plus_in)
66
+ min_in = inv_stdv * (centered_x - 1.0 / 255.0)
67
+ cdf_min = approx_standard_normal_cdf(min_in)
68
+ log_cdf_plus = th.log(cdf_plus.clamp(min=1e-12))
69
+ log_one_minus_cdf_min = th.log((1.0 - cdf_min).clamp(min=1e-12))
70
+ cdf_delta = cdf_plus - cdf_min
71
+ log_probs = th.where(
72
+ x < -0.999,
73
+ log_cdf_plus,
74
+ th.where(x > 0.999, log_one_minus_cdf_min, th.log(cdf_delta.clamp(min=1e-12))),
75
+ )
76
+ assert log_probs.shape == x.shape
77
+ return log_probs
guided_diffusion/guided_diffusion/nn.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Various utilities for neural networks.
3
+ """
4
+
5
+ import math
6
+
7
+ import torch as th
8
+ import torch.nn as nn
9
+
10
+
11
+ # PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
12
+ class SiLU(nn.Module):
13
+ def forward(self, x):
14
+ return x * th.sigmoid(x)
15
+
16
+
17
+ class GroupNorm32(nn.GroupNorm):
18
+ def forward(self, x):
19
+ return super().forward(x.float()).type(x.dtype)
20
+
21
+
22
+ def conv_nd(dims, *args, **kwargs):
23
+ """
24
+ Create a 1D, 2D, or 3D convolution module.
25
+ """
26
+ if dims == 1:
27
+ return nn.Conv1d(*args, **kwargs)
28
+ elif dims == 2:
29
+ return nn.Conv2d(*args, **kwargs)
30
+ elif dims == 3:
31
+ return nn.Conv3d(*args, **kwargs)
32
+ raise ValueError(f"unsupported dimensions: {dims}")
33
+
34
+
35
+ def linear(*args, **kwargs):
36
+ """
37
+ Create a linear module.
38
+ """
39
+ return nn.Linear(*args, **kwargs)
40
+
41
+
42
+ def avg_pool_nd(dims, *args, **kwargs):
43
+ """
44
+ Create a 1D, 2D, or 3D average pooling module.
45
+ """
46
+ if dims == 1:
47
+ return nn.AvgPool1d(*args, **kwargs)
48
+ elif dims == 2:
49
+ return nn.AvgPool2d(*args, **kwargs)
50
+ elif dims == 3:
51
+ return nn.AvgPool3d(*args, **kwargs)
52
+ raise ValueError(f"unsupported dimensions: {dims}")
53
+
54
+
55
+ def update_ema(target_params, source_params, rate=0.99):
56
+ """
57
+ Update target parameters to be closer to those of source parameters using
58
+ an exponential moving average.
59
+
60
+ :param target_params: the target parameter sequence.
61
+ :param source_params: the source parameter sequence.
62
+ :param rate: the EMA rate (closer to 1 means slower).
63
+ """
64
+ for targ, src in zip(target_params, source_params):
65
+ targ.detach().mul_(rate).add_(src, alpha=1 - rate)
66
+
67
+
68
+ def zero_module(module):
69
+ """
70
+ Zero out the parameters of a module and return it.
71
+ """
72
+ for p in module.parameters():
73
+ p.detach().zero_()
74
+ return module
75
+
76
+
77
+ def scale_module(module, scale):
78
+ """
79
+ Scale the parameters of a module and return it.
80
+ """
81
+ for p in module.parameters():
82
+ p.detach().mul_(scale)
83
+ return module
84
+
85
+
86
+ def mean_flat(tensor):
87
+ """
88
+ Take the mean over all non-batch dimensions.
89
+ """
90
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
91
+
92
+
93
+ def normalization(channels):
94
+ """
95
+ Make a standard normalization layer.
96
+
97
+ :param channels: number of input channels.
98
+ :return: an nn.Module for normalization.
99
+ """
100
+ return GroupNorm32(32, channels)
101
+
102
+
103
+ def timestep_embedding(timesteps, dim, max_period=10000):
104
+ """
105
+ Create sinusoidal timestep embeddings.
106
+
107
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
108
+ These may be fractional.
109
+ :param dim: the dimension of the output.
110
+ :param max_period: controls the minimum frequency of the embeddings.
111
+ :return: an [N x dim] Tensor of positional embeddings.
112
+ """
113
+ half = dim // 2
114
+ freqs = th.exp(
115
+ -math.log(max_period) * th.arange(start=0, end=half, dtype=th.float32) / half
116
+ ).to(device=timesteps.device)
117
+ args = timesteps[:, None].float() * freqs[None]
118
+ embedding = th.cat([th.cos(args), th.sin(args)], dim=-1)
119
+ if dim % 2:
120
+ embedding = th.cat([embedding, th.zeros_like(embedding[:, :1])], dim=-1)
121
+ return embedding
122
+
123
+
124
+ def checkpoint(func, inputs, params, flag):
125
+ """
126
+ Evaluate a function without caching intermediate activations, allowing for
127
+ reduced memory at the expense of extra compute in the backward pass.
128
+
129
+ :param func: the function to evaluate.
130
+ :param inputs: the argument sequence to pass to `func`.
131
+ :param params: a sequence of parameters `func` depends on but does not
132
+ explicitly take as arguments.
133
+ :param flag: if False, disable gradient checkpointing.
134
+ """
135
+ if flag:
136
+ args = tuple(inputs) + tuple(params)
137
+ return CheckpointFunction.apply(func, len(inputs), *args)
138
+ else:
139
+ return func(*inputs)
140
+
141
+
142
+ class CheckpointFunction(th.autograd.Function):
143
+ @staticmethod
144
+ def forward(ctx, run_function, length, *args):
145
+ ctx.run_function = run_function
146
+ ctx.input_tensors = list(args[:length])
147
+ ctx.input_params = list(args[length:])
148
+ with th.no_grad():
149
+ output_tensors = ctx.run_function(*ctx.input_tensors)
150
+ return output_tensors
151
+
152
+ @staticmethod
153
+ def backward(ctx, *output_grads):
154
+ ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
155
+ with th.enable_grad():
156
+ # Fixes a bug where the first op in run_function modifies the
157
+ # Tensor storage in place, which is not allowed for detach()'d
158
+ # Tensors.
159
+ shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
160
+ output_tensors = ctx.run_function(*shallow_copies)
161
+ input_grads = th.autograd.grad(
162
+ output_tensors,
163
+ ctx.input_tensors + ctx.input_params,
164
+ output_grads,
165
+ allow_unused=True,
166
+ )
167
+ #del ctx.input_tensors
168
+ #del ctx.input_params
169
+ del output_tensors
170
+ return (None, None) + input_grads
guided_diffusion/guided_diffusion/resample.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+
3
+ import numpy as np
4
+ import torch as th
5
+ import torch.distributed as dist
6
+
7
+
8
+ def create_named_schedule_sampler(name, diffusion):
9
+ """
10
+ Create a ScheduleSampler from a library of pre-defined samplers.
11
+
12
+ :param name: the name of the sampler.
13
+ :param diffusion: the diffusion object to sample for.
14
+ """
15
+ if name == "uniform":
16
+ return UniformSampler(diffusion)
17
+ elif name == "loss-second-moment":
18
+ return LossSecondMomentResampler(diffusion)
19
+ else:
20
+ raise NotImplementedError(f"unknown schedule sampler: {name}")
21
+
22
+
23
+ class ScheduleSampler(ABC):
24
+ """
25
+ A distribution over timesteps in the diffusion process, intended to reduce
26
+ variance of the objective.
27
+
28
+ By default, samplers perform unbiased importance sampling, in which the
29
+ objective's mean is unchanged.
30
+ However, subclasses may override sample() to change how the resampled
31
+ terms are reweighted, allowing for actual changes in the objective.
32
+ """
33
+
34
+ @abstractmethod
35
+ def weights(self):
36
+ """
37
+ Get a numpy array of weights, one per diffusion step.
38
+
39
+ The weights needn't be normalized, but must be positive.
40
+ """
41
+
42
+ def sample(self, batch_size, device):
43
+ """
44
+ Importance-sample timesteps for a batch.
45
+
46
+ :param batch_size: the number of timesteps.
47
+ :param device: the torch device to save to.
48
+ :return: a tuple (timesteps, weights):
49
+ - timesteps: a tensor of timestep indices.
50
+ - weights: a tensor of weights to scale the resulting losses.
51
+ """
52
+ w = self.weights()
53
+ p = w / np.sum(w)
54
+ indices_np = np.random.choice(len(p), size=(batch_size,), p=p)
55
+ indices = th.from_numpy(indices_np).long().to(device)
56
+ weights_np = 1 / (len(p) * p[indices_np])
57
+ weights = th.from_numpy(weights_np).float().to(device)
58
+ return indices, weights
59
+
60
+
61
+ class UniformSampler(ScheduleSampler):
62
+ def __init__(self, diffusion):
63
+ self.diffusion = diffusion
64
+ self._weights = np.ones([diffusion.num_timesteps])
65
+
66
+ def weights(self):
67
+ return self._weights
68
+
69
+
70
+ class LossAwareSampler(ScheduleSampler):
71
+ def update_with_local_losses(self, local_ts, local_losses):
72
+ """
73
+ Update the reweighting using losses from a model.
74
+
75
+ Call this method from each rank with a batch of timesteps and the
76
+ corresponding losses for each of those timesteps.
77
+ This method will perform synchronization to make sure all of the ranks
78
+ maintain the exact same reweighting.
79
+
80
+ :param local_ts: an integer Tensor of timesteps.
81
+ :param local_losses: a 1D Tensor of losses.
82
+ """
83
+ batch_sizes = [
84
+ th.tensor([0], dtype=th.int32, device=local_ts.device)
85
+ for _ in range(dist.get_world_size())
86
+ ]
87
+ dist.all_gather(
88
+ batch_sizes,
89
+ th.tensor([len(local_ts)], dtype=th.int32, device=local_ts.device),
90
+ )
91
+
92
+ # Pad all_gather batches to be the maximum batch size.
93
+ batch_sizes = [x.item() for x in batch_sizes]
94
+ max_bs = max(batch_sizes)
95
+
96
+ timestep_batches = [th.zeros(max_bs).to(local_ts) for bs in batch_sizes]
97
+ loss_batches = [th.zeros(max_bs).to(local_losses) for bs in batch_sizes]
98
+ dist.all_gather(timestep_batches, local_ts)
99
+ dist.all_gather(loss_batches, local_losses)
100
+ timesteps = [
101
+ x.item() for y, bs in zip(timestep_batches, batch_sizes) for x in y[:bs]
102
+ ]
103
+ losses = [x.item() for y, bs in zip(loss_batches, batch_sizes) for x in y[:bs]]
104
+ self.update_with_all_losses(timesteps, losses)
105
+
106
+ @abstractmethod
107
+ def update_with_all_losses(self, ts, losses):
108
+ """
109
+ Update the reweighting using losses from a model.
110
+
111
+ Sub-classes should override this method to update the reweighting
112
+ using losses from the model.
113
+
114
+ This method directly updates the reweighting without synchronizing
115
+ between workers. It is called by update_with_local_losses from all
116
+ ranks with identical arguments. Thus, it should have deterministic
117
+ behavior to maintain state across workers.
118
+
119
+ :param ts: a list of int timesteps.
120
+ :param losses: a list of float losses, one per timestep.
121
+ """
122
+
123
+
124
+ class LossSecondMomentResampler(LossAwareSampler):
125
+ def __init__(self, diffusion, history_per_term=10, uniform_prob=0.001):
126
+ self.diffusion = diffusion
127
+ self.history_per_term = history_per_term
128
+ self.uniform_prob = uniform_prob
129
+ self._loss_history = np.zeros(
130
+ [diffusion.num_timesteps, history_per_term], dtype=np.float64
131
+ )
132
+ self._loss_counts = np.zeros([diffusion.num_timesteps], dtype=np.int)
133
+
134
+ def weights(self):
135
+ if not self._warmed_up():
136
+ return np.ones([self.diffusion.num_timesteps], dtype=np.float64)
137
+ weights = np.sqrt(np.mean(self._loss_history ** 2, axis=-1))
138
+ weights /= np.sum(weights)
139
+ weights *= 1 - self.uniform_prob
140
+ weights += self.uniform_prob / len(weights)
141
+ return weights
142
+
143
+ def update_with_all_losses(self, ts, losses):
144
+ for t, loss in zip(ts, losses):
145
+ if self._loss_counts[t] == self.history_per_term:
146
+ # Shift out the oldest loss term.
147
+ self._loss_history[t, :-1] = self._loss_history[t, 1:]
148
+ self._loss_history[t, -1] = loss
149
+ else:
150
+ self._loss_history[t, self._loss_counts[t]] = loss
151
+ self._loss_counts[t] += 1
152
+
153
+ def _warmed_up(self):
154
+ return (self._loss_counts == self.history_per_term).all()
guided_diffusion/guided_diffusion/respace.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch as th
3
+
4
+ from .gaussian_diffusion import GaussianDiffusion
5
+
6
+
7
+ def space_timesteps(num_timesteps, section_counts):
8
+ """
9
+ Create a list of timesteps to use from an original diffusion process,
10
+ given the number of timesteps we want to take from equally-sized portions
11
+ of the original process.
12
+
13
+ For example, if there's 300 timesteps and the section counts are [10,15,20]
14
+ then the first 100 timesteps are strided to be 10 timesteps, the second 100
15
+ are strided to be 15 timesteps, and the final 100 are strided to be 20.
16
+
17
+ If the stride is a string starting with "ddim", then the fixed striding
18
+ from the DDIM paper is used, and only one section is allowed.
19
+
20
+ :param num_timesteps: the number of diffusion steps in the original
21
+ process to divide up.
22
+ :param section_counts: either a list of numbers, or a string containing
23
+ comma-separated numbers, indicating the step count
24
+ per section. As a special case, use "ddimN" where N
25
+ is a number of steps to use the striding from the
26
+ DDIM paper.
27
+ :return: a set of diffusion steps from the original process to use.
28
+ """
29
+ if isinstance(section_counts, str):
30
+ if section_counts.startswith("ddim"):
31
+ desired_count = int(section_counts[len("ddim") :])
32
+ for i in range(1, num_timesteps):
33
+ if len(range(0, num_timesteps, i)) == desired_count:
34
+ return set(range(0, num_timesteps, i))
35
+ raise ValueError(
36
+ f"cannot create exactly {num_timesteps} steps with an integer stride"
37
+ )
38
+ section_counts = [int(x) for x in section_counts.split(",")]
39
+ size_per = num_timesteps // len(section_counts)
40
+ extra = num_timesteps % len(section_counts)
41
+ start_idx = 0
42
+ all_steps = []
43
+ for i, section_count in enumerate(section_counts):
44
+ size = size_per + (1 if i < extra else 0)
45
+ if size < section_count:
46
+ raise ValueError(
47
+ f"cannot divide section of {size} steps into {section_count}"
48
+ )
49
+ if section_count <= 1:
50
+ frac_stride = 1
51
+ else:
52
+ frac_stride = (size - 1) / (section_count - 1)
53
+ cur_idx = 0.0
54
+ taken_steps = []
55
+ for _ in range(section_count):
56
+ taken_steps.append(start_idx + round(cur_idx))
57
+ cur_idx += frac_stride
58
+ all_steps += taken_steps
59
+ start_idx += size
60
+ return set(all_steps)
61
+
62
+
63
+ class SpacedDiffusion(GaussianDiffusion):
64
+ """
65
+ A diffusion process which can skip steps in a base diffusion process.
66
+
67
+ :param use_timesteps: a collection (sequence or set) of timesteps from the
68
+ original diffusion process to retain.
69
+ :param kwargs: the kwargs to create the base diffusion process.
70
+ """
71
+
72
+ def __init__(self, use_timesteps, **kwargs):
73
+ self.use_timesteps = set(use_timesteps)
74
+ self.timestep_map = []
75
+ self.original_num_steps = len(kwargs["betas"])
76
+
77
+ base_diffusion = GaussianDiffusion(**kwargs) # pylint: disable=missing-kwoa
78
+ last_alpha_cumprod = 1.0
79
+ new_betas = []
80
+ for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod):
81
+ if i in self.use_timesteps:
82
+ new_betas.append(1 - alpha_cumprod / last_alpha_cumprod)
83
+ last_alpha_cumprod = alpha_cumprod
84
+ self.timestep_map.append(i)
85
+ kwargs["betas"] = np.array(new_betas)
86
+ super().__init__(**kwargs)
87
+
88
+ def p_mean_variance(
89
+ self, model, *args, **kwargs
90
+ ): # pylint: disable=signature-differs
91
+ return super().p_mean_variance(self._wrap_model(model), *args, **kwargs)
92
+
93
+ def training_losses(
94
+ self, model, *args, **kwargs
95
+ ): # pylint: disable=signature-differs
96
+ return super().training_losses(self._wrap_model(model), *args, **kwargs)
97
+
98
+ def condition_mean(self, cond_fn, *args, **kwargs):
99
+ return super().condition_mean(self._wrap_model(cond_fn), *args, **kwargs)
100
+
101
+ def condition_score(self, cond_fn, *args, **kwargs):
102
+ return super().condition_score(self._wrap_model(cond_fn), *args, **kwargs)
103
+
104
+ def _wrap_model(self, model):
105
+ if isinstance(model, _WrappedModel):
106
+ return model
107
+ return _WrappedModel(
108
+ model, self.timestep_map, self.rescale_timesteps, self.original_num_steps
109
+ )
110
+
111
+ def _scale_timesteps(self, t):
112
+ # Scaling is done by the wrapped model.
113
+ return t
114
+
115
+
116
+ class _WrappedModel:
117
+ def __init__(self, model, timestep_map, rescale_timesteps, original_num_steps):
118
+ self.model = model
119
+ self.timestep_map = timestep_map
120
+ self.rescale_timesteps = rescale_timesteps
121
+ self.original_num_steps = original_num_steps
122
+
123
+ def __call__(self, x, ts, **kwargs):
124
+ map_tensor = th.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype)
125
+ new_ts = map_tensor[ts]
126
+ if self.rescale_timesteps:
127
+ new_ts = new_ts.float() * (1000.0 / self.original_num_steps)
128
+ return self.model(x, new_ts, **kwargs)
guided_diffusion/guided_diffusion/script_util.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import inspect
3
+
4
+ from . import gaussian_diffusion as gd
5
+ from .respace import SpacedDiffusion, space_timesteps
6
+ from .unet import SuperResModel, UNetModel, EncoderUNetModel
7
+
8
+ NUM_CLASSES = 1000
9
+
10
+
11
+ def diffusion_defaults():
12
+ """
13
+ Defaults for image and classifier training.
14
+ """
15
+ return dict(
16
+ learn_sigma=False,
17
+ diffusion_steps=1000,
18
+ noise_schedule="linear",
19
+ timestep_respacing="",
20
+ use_kl=False,
21
+ predict_xstart=False,
22
+ rescale_timesteps=False,
23
+ rescale_learned_sigmas=False,
24
+ )
25
+
26
+
27
+ def classifier_defaults():
28
+ """
29
+ Defaults for classifier models.
30
+ """
31
+ return dict(
32
+ image_size=256,#64,
33
+ classifier_use_fp16=False,
34
+ classifier_width=128,
35
+ classifier_depth=2,
36
+ classifier_attention_resolutions="32,16,8", # 16
37
+ classifier_use_scale_shift_norm=True, # False
38
+ classifier_resblock_updown=True, # False
39
+ classifier_pool="attention",
40
+ )
41
+
42
+
43
+ def model_and_diffusion_defaults():
44
+ """
45
+ Defaults for image training.
46
+ """
47
+ res = dict(
48
+ image_size=64,
49
+ num_channels=128,
50
+ num_res_blocks=2,
51
+ num_heads=4,
52
+ num_heads_upsample=-1,
53
+ num_head_channels=-1,
54
+ attention_resolutions="16,8",
55
+ channel_mult="",
56
+ dropout=0.0,
57
+ class_cond=False,
58
+ use_checkpoint=False,
59
+ use_scale_shift_norm=True,
60
+ resblock_updown=False,
61
+ use_fp16=False,
62
+ use_new_attention_order=False,
63
+ )
64
+ res.update(diffusion_defaults())
65
+ return res
66
+
67
+
68
+ def classifier_and_diffusion_defaults():
69
+ res = classifier_defaults()
70
+ res.update(diffusion_defaults())
71
+ return res
72
+
73
+
74
+ def create_model_and_diffusion(
75
+ image_size,
76
+ class_cond,
77
+ learn_sigma,
78
+ num_channels,
79
+ num_res_blocks,
80
+ channel_mult,
81
+ num_heads,
82
+ num_head_channels,
83
+ num_heads_upsample,
84
+ attention_resolutions,
85
+ dropout,
86
+ diffusion_steps,
87
+ noise_schedule,
88
+ timestep_respacing,
89
+ use_kl,
90
+ predict_xstart,
91
+ rescale_timesteps,
92
+ rescale_learned_sigmas,
93
+ use_checkpoint,
94
+ use_scale_shift_norm,
95
+ resblock_updown,
96
+ use_fp16,
97
+ use_new_attention_order,
98
+ ):
99
+ model = create_model(
100
+ image_size,
101
+ num_channels,
102
+ num_res_blocks,
103
+ channel_mult=channel_mult,
104
+ learn_sigma=learn_sigma,
105
+ class_cond=class_cond,
106
+ use_checkpoint=use_checkpoint,
107
+ attention_resolutions=attention_resolutions,
108
+ num_heads=num_heads,
109
+ num_head_channels=num_head_channels,
110
+ num_heads_upsample=num_heads_upsample,
111
+ use_scale_shift_norm=use_scale_shift_norm,
112
+ dropout=dropout,
113
+ resblock_updown=resblock_updown,
114
+ use_fp16=use_fp16,
115
+ use_new_attention_order=use_new_attention_order,
116
+ )
117
+ diffusion = create_gaussian_diffusion(
118
+ steps=diffusion_steps,
119
+ learn_sigma=learn_sigma,
120
+ noise_schedule=noise_schedule,
121
+ use_kl=use_kl,
122
+ predict_xstart=predict_xstart,
123
+ rescale_timesteps=rescale_timesteps,
124
+ rescale_learned_sigmas=rescale_learned_sigmas,
125
+ timestep_respacing=timestep_respacing,
126
+ )
127
+ return model, diffusion
128
+
129
+
130
+ def create_model(
131
+ image_size,
132
+ num_channels,
133
+ num_res_blocks,
134
+ channel_mult="",
135
+ learn_sigma=False,
136
+ class_cond=False,
137
+ use_checkpoint=False,
138
+ attention_resolutions="16",
139
+ num_heads=1,
140
+ num_head_channels=-1,
141
+ num_heads_upsample=-1,
142
+ use_scale_shift_norm=False,
143
+ dropout=0,
144
+ resblock_updown=False,
145
+ use_fp16=False,
146
+ use_new_attention_order=False,
147
+ ):
148
+ if channel_mult == "":
149
+ if image_size == 512:
150
+ channel_mult = (0.5, 1, 1, 2, 2, 4, 4)
151
+ elif image_size == 256:
152
+ channel_mult = (1, 1, 2, 2, 4, 4)
153
+ elif image_size == 128:
154
+ channel_mult = (1, 1, 2, 3, 4)
155
+ elif image_size == 64:
156
+ channel_mult = (1, 2, 3, 4)
157
+ else:
158
+ raise ValueError(f"unsupported image size: {image_size}")
159
+ else:
160
+ channel_mult = tuple(int(ch_mult) for ch_mult in channel_mult.split(","))
161
+
162
+ attention_ds = []
163
+ for res in attention_resolutions.split(","):
164
+ attention_ds.append(image_size // int(res))
165
+
166
+ return UNetModel(
167
+ image_size=image_size,
168
+ in_channels=3,
169
+ model_channels=num_channels,
170
+ out_channels=(3 if not learn_sigma else 6),
171
+ num_res_blocks=num_res_blocks,
172
+ attention_resolutions=tuple(attention_ds),
173
+ dropout=dropout,
174
+ channel_mult=channel_mult,
175
+ num_classes=(NUM_CLASSES if class_cond else None),
176
+ use_checkpoint=use_checkpoint,
177
+ use_fp16=use_fp16,
178
+ num_heads=num_heads,
179
+ num_head_channels=num_head_channels,
180
+ num_heads_upsample=num_heads_upsample,
181
+ use_scale_shift_norm=use_scale_shift_norm,
182
+ resblock_updown=resblock_updown,
183
+ use_new_attention_order=use_new_attention_order,
184
+ )
185
+
186
+
187
+ def create_classifier_and_diffusion(
188
+ image_size,
189
+ classifier_use_fp16,
190
+ classifier_width,
191
+ classifier_depth,
192
+ classifier_attention_resolutions,
193
+ classifier_use_scale_shift_norm,
194
+ classifier_resblock_updown,
195
+ classifier_pool,
196
+ learn_sigma,
197
+ diffusion_steps,
198
+ noise_schedule,
199
+ timestep_respacing,
200
+ use_kl,
201
+ predict_xstart,
202
+ rescale_timesteps,
203
+ rescale_learned_sigmas,
204
+ ):
205
+ classifier = create_classifier(
206
+ image_size,
207
+ classifier_use_fp16,
208
+ classifier_width,
209
+ classifier_depth,
210
+ classifier_attention_resolutions,
211
+ classifier_use_scale_shift_norm,
212
+ classifier_resblock_updown,
213
+ classifier_pool,
214
+ )
215
+ diffusion = create_gaussian_diffusion(
216
+ steps=diffusion_steps,
217
+ learn_sigma=learn_sigma,
218
+ noise_schedule=noise_schedule,
219
+ use_kl=use_kl,
220
+ predict_xstart=predict_xstart,
221
+ rescale_timesteps=rescale_timesteps,
222
+ rescale_learned_sigmas=rescale_learned_sigmas,
223
+ timestep_respacing=timestep_respacing,
224
+ )
225
+ return classifier, diffusion
226
+
227
+
228
+ def create_classifier(
229
+ image_size,
230
+ classifier_use_fp16,
231
+ classifier_width,
232
+ classifier_depth,
233
+ classifier_attention_resolutions,
234
+ classifier_use_scale_shift_norm,
235
+ classifier_resblock_updown,
236
+ classifier_pool,
237
+ ):
238
+ if image_size == 512:
239
+ channel_mult = (0.5, 1, 1, 2, 2, 4, 4)
240
+ elif image_size == 256:
241
+ channel_mult = (1, 1, 2, 2, 4, 4)
242
+ elif image_size == 128:
243
+ channel_mult = (1, 1, 2, 3, 4)
244
+ elif image_size == 64:
245
+ channel_mult = (1, 2, 3, 4)
246
+ else:
247
+ raise ValueError(f"unsupported image size: {image_size}")
248
+
249
+ attention_ds = []
250
+ for res in classifier_attention_resolutions.split(","):
251
+ attention_ds.append(image_size // int(res))
252
+
253
+ return EncoderUNetModel(
254
+ image_size=image_size,
255
+ in_channels=3,
256
+ model_channels=classifier_width,
257
+ out_channels=1000,
258
+ num_res_blocks=classifier_depth,
259
+ attention_resolutions=tuple(attention_ds),
260
+ channel_mult=channel_mult,
261
+ use_fp16=classifier_use_fp16,
262
+ num_head_channels=64,
263
+ use_scale_shift_norm=classifier_use_scale_shift_norm,
264
+ resblock_updown=classifier_resblock_updown,
265
+ pool=classifier_pool,
266
+ )
267
+
268
+
269
+ def sr_model_and_diffusion_defaults():
270
+ res = model_and_diffusion_defaults()
271
+ res["large_size"] = 256
272
+ res["small_size"] = 64
273
+ arg_names = inspect.getfullargspec(sr_create_model_and_diffusion)[0]
274
+ for k in res.copy().keys():
275
+ if k not in arg_names:
276
+ del res[k]
277
+ return res
278
+
279
+
280
+ def sr_create_model_and_diffusion(
281
+ large_size,
282
+ small_size,
283
+ class_cond,
284
+ learn_sigma,
285
+ num_channels,
286
+ num_res_blocks,
287
+ num_heads,
288
+ num_head_channels,
289
+ num_heads_upsample,
290
+ attention_resolutions,
291
+ dropout,
292
+ diffusion_steps,
293
+ noise_schedule,
294
+ timestep_respacing,
295
+ use_kl,
296
+ predict_xstart,
297
+ rescale_timesteps,
298
+ rescale_learned_sigmas,
299
+ use_checkpoint,
300
+ use_scale_shift_norm,
301
+ resblock_updown,
302
+ use_fp16,
303
+ ):
304
+ model = sr_create_model(
305
+ large_size,
306
+ small_size,
307
+ num_channels,
308
+ num_res_blocks,
309
+ learn_sigma=learn_sigma,
310
+ class_cond=class_cond,
311
+ use_checkpoint=use_checkpoint,
312
+ attention_resolutions=attention_resolutions,
313
+ num_heads=num_heads,
314
+ num_head_channels=num_head_channels,
315
+ num_heads_upsample=num_heads_upsample,
316
+ use_scale_shift_norm=use_scale_shift_norm,
317
+ dropout=dropout,
318
+ resblock_updown=resblock_updown,
319
+ use_fp16=use_fp16,
320
+ )
321
+ diffusion = create_gaussian_diffusion(
322
+ steps=diffusion_steps,
323
+ learn_sigma=learn_sigma,
324
+ noise_schedule=noise_schedule,
325
+ use_kl=use_kl,
326
+ predict_xstart=predict_xstart,
327
+ rescale_timesteps=rescale_timesteps,
328
+ rescale_learned_sigmas=rescale_learned_sigmas,
329
+ timestep_respacing=timestep_respacing,
330
+ )
331
+ return model, diffusion
332
+
333
+
334
+ def sr_create_model(
335
+ large_size,
336
+ small_size,
337
+ num_channels,
338
+ num_res_blocks,
339
+ learn_sigma,
340
+ class_cond,
341
+ use_checkpoint,
342
+ attention_resolutions,
343
+ num_heads,
344
+ num_head_channels,
345
+ num_heads_upsample,
346
+ use_scale_shift_norm,
347
+ dropout,
348
+ resblock_updown,
349
+ use_fp16,
350
+ ):
351
+ _ = small_size # hack to prevent unused variable
352
+
353
+ if large_size == 512:
354
+ channel_mult = (1, 1, 2, 2, 4, 4)
355
+ elif large_size == 256:
356
+ channel_mult = (1, 1, 2, 2, 4, 4)
357
+ elif large_size == 64:
358
+ channel_mult = (1, 2, 3, 4)
359
+ else:
360
+ raise ValueError(f"unsupported large size: {large_size}")
361
+
362
+ attention_ds = []
363
+ for res in attention_resolutions.split(","):
364
+ attention_ds.append(large_size // int(res))
365
+
366
+ return SuperResModel(
367
+ image_size=large_size,
368
+ in_channels=3,
369
+ model_channels=num_channels,
370
+ out_channels=(3 if not learn_sigma else 6),
371
+ num_res_blocks=num_res_blocks,
372
+ attention_resolutions=tuple(attention_ds),
373
+ dropout=dropout,
374
+ channel_mult=channel_mult,
375
+ num_classes=(NUM_CLASSES if class_cond else None),
376
+ use_checkpoint=use_checkpoint,
377
+ num_heads=num_heads,
378
+ num_head_channels=num_head_channels,
379
+ num_heads_upsample=num_heads_upsample,
380
+ use_scale_shift_norm=use_scale_shift_norm,
381
+ resblock_updown=resblock_updown,
382
+ use_fp16=use_fp16,
383
+ )
384
+
385
+
386
+ def create_gaussian_diffusion(
387
+ *,
388
+ steps=1000,
389
+ learn_sigma=False,
390
+ sigma_small=False,
391
+ noise_schedule="linear",
392
+ use_kl=False,
393
+ predict_xstart=False,
394
+ rescale_timesteps=False,
395
+ rescale_learned_sigmas=False,
396
+ timestep_respacing="",
397
+ ):
398
+ betas = gd.get_named_beta_schedule(noise_schedule, steps)
399
+ if use_kl:
400
+ loss_type = gd.LossType.RESCALED_KL
401
+ elif rescale_learned_sigmas:
402
+ loss_type = gd.LossType.RESCALED_MSE
403
+ else:
404
+ loss_type = gd.LossType.MSE
405
+ if not timestep_respacing:
406
+ timestep_respacing = [steps]
407
+ return SpacedDiffusion(
408
+ use_timesteps=space_timesteps(steps, timestep_respacing),
409
+ betas=betas,
410
+ model_mean_type=(
411
+ gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X
412
+ ),
413
+ model_var_type=(
414
+ (
415
+ gd.ModelVarType.FIXED_LARGE
416
+ if not sigma_small
417
+ else gd.ModelVarType.FIXED_SMALL
418
+ )
419
+ if not learn_sigma
420
+ else gd.ModelVarType.LEARNED_RANGE
421
+ ),
422
+ loss_type=loss_type,
423
+ rescale_timesteps=rescale_timesteps,
424
+ )
425
+
426
+
427
+ def add_dict_to_argparser(parser, default_dict):
428
+ for k, v in default_dict.items():
429
+ v_type = type(v)
430
+ if v is None:
431
+ v_type = str
432
+ elif isinstance(v, bool):
433
+ v_type = str2bool
434
+ parser.add_argument(f"--{k}", default=v, type=v_type)
435
+
436
+
437
+ def args_to_dict(args, keys):
438
+ return {k: getattr(args, k) for k in keys}
439
+
440
+
441
+ def str2bool(v):
442
+ """
443
+ https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
444
+ """
445
+ if isinstance(v, bool):
446
+ return v
447
+ if v.lower() in ("yes", "true", "t", "y", "1"):
448
+ return True
449
+ elif v.lower() in ("no", "false", "f", "n", "0"):
450
+ return False
451
+ else:
452
+ raise argparse.ArgumentTypeError("boolean value expected")
guided_diffusion/guided_diffusion/train_util.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import functools
3
+ import os
4
+
5
+ import blobfile as bf
6
+ import torch as th
7
+ import torch.distributed as dist
8
+ from torch.nn.parallel.distributed import DistributedDataParallel as DDP
9
+ from torch.optim import AdamW
10
+
11
+ from . import dist_util, logger
12
+ from .fp16_util import MixedPrecisionTrainer
13
+ from .nn import update_ema
14
+ from .resample import LossAwareSampler, UniformSampler
15
+
16
+ # For ImageNet experiments, this was a good default value.
17
+ # We found that the lg_loss_scale quickly climbed to
18
+ # 20-21 within the first ~1K steps of training.
19
+ INITIAL_LOG_LOSS_SCALE = 20.0
20
+
21
+
22
+ class TrainLoop:
23
+ def __init__(
24
+ self,
25
+ *,
26
+ model,
27
+ diffusion,
28
+ data,
29
+ batch_size,
30
+ microbatch,
31
+ lr,
32
+ ema_rate,
33
+ log_interval,
34
+ save_interval,
35
+ resume_checkpoint,
36
+ use_fp16=False,
37
+ fp16_scale_growth=1e-3,
38
+ schedule_sampler=None,
39
+ weight_decay=0.0,
40
+ lr_anneal_steps=0,
41
+ ):
42
+ self.model = model
43
+ self.diffusion = diffusion
44
+ self.data = data
45
+ self.batch_size = batch_size
46
+ self.microbatch = microbatch if microbatch > 0 else batch_size
47
+ self.lr = lr
48
+ self.ema_rate = (
49
+ [ema_rate]
50
+ if isinstance(ema_rate, float)
51
+ else [float(x) for x in ema_rate.split(",")]
52
+ )
53
+ self.log_interval = log_interval
54
+ self.save_interval = save_interval
55
+ self.resume_checkpoint = resume_checkpoint
56
+ self.use_fp16 = use_fp16
57
+ self.fp16_scale_growth = fp16_scale_growth
58
+ self.schedule_sampler = schedule_sampler or UniformSampler(diffusion)
59
+ self.weight_decay = weight_decay
60
+ self.lr_anneal_steps = lr_anneal_steps
61
+
62
+ self.step = 0
63
+ self.resume_step = 0
64
+ self.global_batch = self.batch_size * dist.get_world_size()
65
+
66
+ self.sync_cuda = th.cuda.is_available()
67
+
68
+ self._load_and_sync_parameters()
69
+ self.mp_trainer = MixedPrecisionTrainer(
70
+ model=self.model,
71
+ use_fp16=self.use_fp16,
72
+ fp16_scale_growth=fp16_scale_growth,
73
+ )
74
+
75
+ self.opt = AdamW(
76
+ self.mp_trainer.master_params, lr=self.lr, weight_decay=self.weight_decay
77
+ )
78
+ if self.resume_step:
79
+ self._load_optimizer_state()
80
+ # Model was resumed, either due to a restart or a checkpoint
81
+ # being specified at the command line.
82
+ self.ema_params = [
83
+ self._load_ema_parameters(rate) for rate in self.ema_rate
84
+ ]
85
+ else:
86
+ self.ema_params = [
87
+ copy.deepcopy(self.mp_trainer.master_params)
88
+ for _ in range(len(self.ema_rate))
89
+ ]
90
+
91
+ if th.cuda.is_available():
92
+ self.use_ddp = True
93
+ self.ddp_model = DDP(
94
+ self.model,
95
+ device_ids=[dist_util.dev()],
96
+ output_device=dist_util.dev(),
97
+ broadcast_buffers=False,
98
+ bucket_cap_mb=128,
99
+ find_unused_parameters=False,
100
+ )
101
+ else:
102
+ if dist.get_world_size() > 1:
103
+ logger.warn(
104
+ "Distributed training requires CUDA. "
105
+ "Gradients will not be synchronized properly!"
106
+ )
107
+ self.use_ddp = False
108
+ self.ddp_model = self.model
109
+
110
+ def _load_and_sync_parameters(self):
111
+ resume_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
112
+
113
+ if resume_checkpoint:
114
+ self.resume_step = parse_resume_step_from_filename(resume_checkpoint)
115
+ if dist.get_rank() == 0:
116
+ logger.log(f"loading model from checkpoint: {resume_checkpoint}...")
117
+ self.model.load_state_dict(
118
+ dist_util.load_state_dict(
119
+ resume_checkpoint, map_location=dist_util.dev()
120
+ )
121
+ )
122
+
123
+ dist_util.sync_params(self.model.parameters())
124
+
125
+ def _load_ema_parameters(self, rate):
126
+ ema_params = copy.deepcopy(self.mp_trainer.master_params)
127
+
128
+ main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
129
+ ema_checkpoint = find_ema_checkpoint(main_checkpoint, self.resume_step, rate)
130
+ if ema_checkpoint:
131
+ if dist.get_rank() == 0:
132
+ logger.log(f"loading EMA from checkpoint: {ema_checkpoint}...")
133
+ state_dict = dist_util.load_state_dict(
134
+ ema_checkpoint, map_location=dist_util.dev()
135
+ )
136
+ ema_params = self.mp_trainer.state_dict_to_master_params(state_dict)
137
+
138
+ dist_util.sync_params(ema_params)
139
+ return ema_params
140
+
141
+ def _load_optimizer_state(self):
142
+ main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
143
+ opt_checkpoint = bf.join(
144
+ bf.dirname(main_checkpoint), f"opt{self.resume_step:06}.pt"
145
+ )
146
+ if bf.exists(opt_checkpoint):
147
+ logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}")
148
+ state_dict = dist_util.load_state_dict(
149
+ opt_checkpoint, map_location=dist_util.dev()
150
+ )
151
+ self.opt.load_state_dict(state_dict)
152
+
153
+ def run_loop(self):
154
+ while (
155
+ not self.lr_anneal_steps
156
+ or self.step + self.resume_step < self.lr_anneal_steps
157
+ ):
158
+ batch, cond = next(self.data)
159
+ self.run_step(batch, cond)
160
+ if self.step % self.log_interval == 0:
161
+ logger.dumpkvs()
162
+ if self.step % self.save_interval == 0:
163
+ self.save()
164
+ # Run for a finite amount of time in integration tests.
165
+ if os.environ.get("DIFFUSION_TRAINING_TEST", "") and self.step > 0:
166
+ return
167
+ self.step += 1
168
+ # Save the last checkpoint if it wasn't already saved.
169
+ if (self.step - 1) % self.save_interval != 0:
170
+ self.save()
171
+
172
+ def run_step(self, batch, cond):
173
+ self.forward_backward(batch, cond)
174
+ took_step = self.mp_trainer.optimize(self.opt)
175
+ if took_step:
176
+ self._update_ema()
177
+ self._anneal_lr()
178
+ self.log_step()
179
+
180
+ def forward_backward(self, batch, cond):
181
+ self.mp_trainer.zero_grad()
182
+ for i in range(0, batch.shape[0], self.microbatch):
183
+ micro = batch[i : i + self.microbatch].to(dist_util.dev())
184
+ micro_cond = {
185
+ k: v[i : i + self.microbatch].to(dist_util.dev())
186
+ for k, v in cond.items()
187
+ }
188
+ last_batch = (i + self.microbatch) >= batch.shape[0]
189
+ t, weights = self.schedule_sampler.sample(micro.shape[0], dist_util.dev())
190
+
191
+ compute_losses = functools.partial(
192
+ self.diffusion.training_losses,
193
+ self.ddp_model,
194
+ micro,
195
+ t,
196
+ model_kwargs=micro_cond,
197
+ )
198
+
199
+ if last_batch or not self.use_ddp:
200
+ losses = compute_losses()
201
+ else:
202
+ with self.ddp_model.no_sync():
203
+ losses = compute_losses()
204
+
205
+ if isinstance(self.schedule_sampler, LossAwareSampler):
206
+ self.schedule_sampler.update_with_local_losses(
207
+ t, losses["loss"].detach()
208
+ )
209
+
210
+ loss = (losses["loss"] * weights).mean()
211
+ log_loss_dict(
212
+ self.diffusion, t, {k: v * weights for k, v in losses.items()}
213
+ )
214
+ self.mp_trainer.backward(loss)
215
+
216
+ def _update_ema(self):
217
+ for rate, params in zip(self.ema_rate, self.ema_params):
218
+ update_ema(params, self.mp_trainer.master_params, rate=rate)
219
+
220
+ def _anneal_lr(self):
221
+ if not self.lr_anneal_steps:
222
+ return
223
+ frac_done = (self.step + self.resume_step) / self.lr_anneal_steps
224
+ lr = self.lr * (1 - frac_done)
225
+ for param_group in self.opt.param_groups:
226
+ param_group["lr"] = lr
227
+
228
+ def log_step(self):
229
+ logger.logkv("step", self.step + self.resume_step)
230
+ logger.logkv("samples", (self.step + self.resume_step + 1) * self.global_batch)
231
+
232
+ def save(self):
233
+ def save_checkpoint(rate, params):
234
+ state_dict = self.mp_trainer.master_params_to_state_dict(params)
235
+ if dist.get_rank() == 0:
236
+ logger.log(f"saving model {rate}...")
237
+ if not rate:
238
+ filename = f"model{(self.step+self.resume_step):06d}.pt"
239
+ else:
240
+ filename = f"ema_{rate}_{(self.step+self.resume_step):06d}.pt"
241
+ with bf.BlobFile(bf.join(get_blob_logdir(), filename), "wb") as f:
242
+ th.save(state_dict, f)
243
+
244
+ save_checkpoint(0, self.mp_trainer.master_params)
245
+ for rate, params in zip(self.ema_rate, self.ema_params):
246
+ save_checkpoint(rate, params)
247
+
248
+ if dist.get_rank() == 0:
249
+ with bf.BlobFile(
250
+ bf.join(get_blob_logdir(), f"opt{(self.step+self.resume_step):06d}.pt"),
251
+ "wb",
252
+ ) as f:
253
+ th.save(self.opt.state_dict(), f)
254
+
255
+ dist.barrier()
256
+
257
+
258
+ def parse_resume_step_from_filename(filename):
259
+ """
260
+ Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the
261
+ checkpoint's number of steps.
262
+ """
263
+ split = filename.split("model")
264
+ if len(split) < 2:
265
+ return 0
266
+ split1 = split[-1].split(".")[0]
267
+ try:
268
+ return int(split1)
269
+ except ValueError:
270
+ return 0
271
+
272
+
273
+ def get_blob_logdir():
274
+ # You can change this to be a separate path to save checkpoints to
275
+ # a blobstore or some external drive.
276
+ return logger.get_dir()
277
+
278
+
279
+ def find_resume_checkpoint():
280
+ # On your infrastructure, you may want to override this to automatically
281
+ # discover the latest checkpoint on your blob storage, etc.
282
+ return None
283
+
284
+
285
+ def find_ema_checkpoint(main_checkpoint, step, rate):
286
+ if main_checkpoint is None:
287
+ return None
288
+ filename = f"ema_{rate}_{(step):06d}.pt"
289
+ path = bf.join(bf.dirname(main_checkpoint), filename)
290
+ if bf.exists(path):
291
+ return path
292
+ return None
293
+
294
+
295
+ def log_loss_dict(diffusion, ts, losses):
296
+ for key, values in losses.items():
297
+ logger.logkv_mean(key, values.mean().item())
298
+ # Log the quantiles (four quartiles, in particular).
299
+ for sub_t, sub_loss in zip(ts.cpu().numpy(), values.detach().cpu().numpy()):
300
+ quartile = int(4 * sub_t / diffusion.num_timesteps)
301
+ logger.logkv_mean(f"{key}_q{quartile}", sub_loss)
guided_diffusion/guided_diffusion/unet.py ADDED
@@ -0,0 +1,908 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch as th
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ from .fp16_util import convert_module_to_f16, convert_module_to_f32
11
+ from .nn import (
12
+ checkpoint,
13
+ conv_nd,
14
+ linear,
15
+ avg_pool_nd,
16
+ zero_module,
17
+ normalization,
18
+ timestep_embedding,
19
+ )
20
+
21
+
22
+ class AttentionPool2d(nn.Module):
23
+ """
24
+ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ spacial_dim: int,
30
+ embed_dim: int,
31
+ num_heads_channels: int,
32
+ output_dim: int = None,
33
+ ):
34
+ super().__init__()
35
+ self.positional_embedding = nn.Parameter(
36
+ th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5
37
+ )
38
+ self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
39
+ self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
40
+ self.num_heads = embed_dim // num_heads_channels
41
+ self.attention = QKVAttention(self.num_heads)
42
+
43
+ def forward(self, x):
44
+ b, c, *_spatial = x.shape
45
+ x = x.reshape(b, c, -1) # NC(HW)
46
+ x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
47
+ x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
48
+ x = self.qkv_proj(x)
49
+ x = self.attention(x)
50
+ x = self.c_proj(x)
51
+ return x[:, :, 0]
52
+
53
+
54
+ class TimestepBlock(nn.Module):
55
+ """
56
+ Any module where forward() takes timestep embeddings as a second argument.
57
+ """
58
+
59
+ @abstractmethod
60
+ def forward(self, x, emb):
61
+ """
62
+ Apply the module to `x` given `emb` timestep embeddings.
63
+ """
64
+
65
+
66
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
67
+ """
68
+ A sequential module that passes timestep embeddings to the children that
69
+ support it as an extra input.
70
+ """
71
+
72
+ def forward(self, x, emb):
73
+ for layer in self:
74
+ if isinstance(layer, TimestepBlock):
75
+ x = layer(x, emb)
76
+ else:
77
+ x = layer(x)
78
+ return x
79
+
80
+
81
+ class Upsample(nn.Module):
82
+ """
83
+ An upsampling layer with an optional convolution.
84
+
85
+ :param channels: channels in the inputs and outputs.
86
+ :param use_conv: a bool determining if a convolution is applied.
87
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
88
+ upsampling occurs in the inner-two dimensions.
89
+ """
90
+
91
+ def __init__(self, channels, use_conv, dims=2, out_channels=None):
92
+ super().__init__()
93
+ self.channels = channels
94
+ self.out_channels = out_channels or channels
95
+ self.use_conv = use_conv
96
+ self.dims = dims
97
+ if use_conv:
98
+ self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
99
+
100
+ def forward(self, x):
101
+ assert x.shape[1] == self.channels
102
+ if self.dims == 3:
103
+ x = F.interpolate(
104
+ x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
105
+ )
106
+ else:
107
+ x = F.interpolate(x, scale_factor=2, mode="nearest")
108
+ if self.use_conv:
109
+ x = self.conv(x)
110
+ return x
111
+
112
+
113
+ class Downsample(nn.Module):
114
+ """
115
+ A downsampling layer with an optional convolution.
116
+
117
+ :param channels: channels in the inputs and outputs.
118
+ :param use_conv: a bool determining if a convolution is applied.
119
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
120
+ downsampling occurs in the inner-two dimensions.
121
+ """
122
+
123
+ def __init__(self, channels, use_conv, dims=2, out_channels=None):
124
+ super().__init__()
125
+ self.channels = channels
126
+ self.out_channels = out_channels or channels
127
+ self.use_conv = use_conv
128
+ self.dims = dims
129
+ stride = 2 if dims != 3 else (1, 2, 2)
130
+ if use_conv:
131
+ self.op = conv_nd(
132
+ dims, self.channels, self.out_channels, 3, stride=stride, padding=1
133
+ )
134
+ else:
135
+ assert self.channels == self.out_channels
136
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
137
+
138
+ def forward(self, x):
139
+ assert x.shape[1] == self.channels
140
+ return self.op(x)
141
+
142
+
143
+ class ResBlock(TimestepBlock):
144
+ """
145
+ A residual block that can optionally change the number of channels.
146
+
147
+ :param channels: the number of input channels.
148
+ :param emb_channels: the number of timestep embedding channels.
149
+ :param dropout: the rate of dropout.
150
+ :param out_channels: if specified, the number of out channels.
151
+ :param use_conv: if True and out_channels is specified, use a spatial
152
+ convolution instead of a smaller 1x1 convolution to change the
153
+ channels in the skip connection.
154
+ :param dims: determines if the signal is 1D, 2D, or 3D.
155
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
156
+ :param up: if True, use this block for upsampling.
157
+ :param down: if True, use this block for downsampling.
158
+ """
159
+
160
+ def __init__(
161
+ self,
162
+ channels,
163
+ emb_channels,
164
+ dropout,
165
+ out_channels=None,
166
+ use_conv=False,
167
+ use_scale_shift_norm=False,
168
+ dims=2,
169
+ use_checkpoint=False,
170
+ up=False,
171
+ down=False,
172
+ ):
173
+ super().__init__()
174
+ self.channels = channels
175
+ self.emb_channels = emb_channels
176
+ self.dropout = dropout
177
+ self.out_channels = out_channels or channels
178
+ self.use_conv = use_conv
179
+ self.use_checkpoint = use_checkpoint
180
+ self.use_scale_shift_norm = use_scale_shift_norm
181
+
182
+ self.in_layers = nn.Sequential(
183
+ normalization(channels),
184
+ nn.SiLU(),
185
+ conv_nd(dims, channels, self.out_channels, 3, padding=1),
186
+ )
187
+
188
+ self.updown = up or down
189
+
190
+ if up:
191
+ self.h_upd = Upsample(channels, False, dims)
192
+ self.x_upd = Upsample(channels, False, dims)
193
+ elif down:
194
+ self.h_upd = Downsample(channels, False, dims)
195
+ self.x_upd = Downsample(channels, False, dims)
196
+ else:
197
+ self.h_upd = self.x_upd = nn.Identity()
198
+
199
+ self.emb_layers = nn.Sequential(
200
+ nn.SiLU(),
201
+ linear(
202
+ emb_channels,
203
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
204
+ ),
205
+ )
206
+ self.out_layers = nn.Sequential(
207
+ normalization(self.out_channels),
208
+ nn.SiLU(),
209
+ nn.Dropout(p=dropout),
210
+ zero_module(
211
+ conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
212
+ ),
213
+ )
214
+
215
+ if self.out_channels == channels:
216
+ self.skip_connection = nn.Identity()
217
+ elif use_conv:
218
+ self.skip_connection = conv_nd(
219
+ dims, channels, self.out_channels, 3, padding=1
220
+ )
221
+ else:
222
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
223
+
224
+ def forward(self, x, emb):
225
+ """
226
+ Apply the block to a Tensor, conditioned on a timestep embedding.
227
+
228
+ :param x: an [N x C x ...] Tensor of features.
229
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
230
+ :return: an [N x C x ...] Tensor of outputs.
231
+ """
232
+ return checkpoint(
233
+ self._forward, (x, emb), self.parameters(), self.use_checkpoint
234
+ )
235
+
236
+ def _forward(self, x, emb):
237
+ if self.updown:
238
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
239
+ h = in_rest(x)
240
+ h = self.h_upd(h)
241
+ x = self.x_upd(x)
242
+ h = in_conv(h)
243
+ else:
244
+ h = self.in_layers(x)
245
+ emb_out = self.emb_layers(emb).type(h.dtype)
246
+ while len(emb_out.shape) < len(h.shape):
247
+ emb_out = emb_out[..., None]
248
+ if self.use_scale_shift_norm:
249
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
250
+ scale, shift = th.chunk(emb_out, 2, dim=1)
251
+ h = out_norm(h) * (1 + scale) + shift
252
+ h = out_rest(h)
253
+ else:
254
+ h = h + emb_out
255
+ h = self.out_layers(h)
256
+ return self.skip_connection(x) + h
257
+
258
+
259
+ class AttentionBlock(nn.Module):
260
+ """
261
+ An attention block that allows spatial positions to attend to each other.
262
+
263
+ Originally ported from here, but adapted to the N-d case.
264
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
265
+ """
266
+
267
+ def __init__(
268
+ self,
269
+ channels,
270
+ num_heads=1,
271
+ num_head_channels=-1,
272
+ use_checkpoint=False,
273
+ use_new_attention_order=False,
274
+ ):
275
+ super().__init__()
276
+ self.channels = channels
277
+ if num_head_channels == -1:
278
+ self.num_heads = num_heads
279
+ else:
280
+ assert (
281
+ channels % num_head_channels == 0
282
+ ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
283
+ self.num_heads = channels // num_head_channels
284
+ self.use_checkpoint = use_checkpoint
285
+ self.norm = normalization(channels)
286
+ self.qkv = conv_nd(1, channels, channels * 3, 1)
287
+ if use_new_attention_order:
288
+ # split qkv before split heads
289
+ self.attention = QKVAttention(self.num_heads)
290
+ else:
291
+ # split heads before split qkv
292
+ self.attention = QKVAttentionLegacy(self.num_heads)
293
+
294
+ self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
295
+
296
+ def forward(self, x):
297
+ return checkpoint(self._forward, (x,), self.parameters(), True)
298
+
299
+ def _forward(self, x):
300
+ b, c, *spatial = x.shape
301
+ x = x.reshape(b, c, -1)
302
+ qkv = self.qkv(self.norm(x))
303
+ h = self.attention(qkv)
304
+ h = self.proj_out(h)
305
+ return (x + h).reshape(b, c, *spatial)
306
+
307
+
308
+ def count_flops_attn(model, _x, y):
309
+ """
310
+ A counter for the `thop` package to count the operations in an
311
+ attention operation.
312
+ Meant to be used like:
313
+ macs, params = thop.profile(
314
+ model,
315
+ inputs=(inputs, timestamps),
316
+ custom_ops={QKVAttention: QKVAttention.count_flops},
317
+ )
318
+ """
319
+ b, c, *spatial = y[0].shape
320
+ num_spatial = int(np.prod(spatial))
321
+ # We perform two matmuls with the same number of ops.
322
+ # The first computes the weight matrix, the second computes
323
+ # the combination of the value vectors.
324
+ matmul_ops = 2 * b * (num_spatial ** 2) * c
325
+ model.total_ops += th.DoubleTensor([matmul_ops])
326
+
327
+
328
+ class QKVAttentionLegacy(nn.Module):
329
+ """
330
+ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
331
+ """
332
+
333
+ def __init__(self, n_heads):
334
+ super().__init__()
335
+ self.n_heads = n_heads
336
+
337
+ def forward(self, qkv):
338
+ """
339
+ Apply QKV attention.
340
+
341
+ :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
342
+ :return: an [N x (H * C) x T] tensor after attention.
343
+ """
344
+ bs, width, length = qkv.shape
345
+ assert width % (3 * self.n_heads) == 0
346
+ ch = width // (3 * self.n_heads)
347
+ q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
348
+ scale = 1 / math.sqrt(math.sqrt(ch))
349
+ weight = th.einsum(
350
+ "bct,bcs->bts", q * scale, k * scale
351
+ ) # More stable with f16 than dividing afterwards
352
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
353
+ a = th.einsum("bts,bcs->bct", weight, v)
354
+ return a.reshape(bs, -1, length)
355
+
356
+ @staticmethod
357
+ def count_flops(model, _x, y):
358
+ return count_flops_attn(model, _x, y)
359
+
360
+
361
+ class QKVAttention(nn.Module):
362
+ """
363
+ A module which performs QKV attention and splits in a different order.
364
+ """
365
+
366
+ def __init__(self, n_heads):
367
+ super().__init__()
368
+ self.n_heads = n_heads
369
+
370
+ def forward(self, qkv):
371
+ """
372
+ Apply QKV attention.
373
+
374
+ :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
375
+ :return: an [N x (H * C) x T] tensor after attention.
376
+ """
377
+ bs, width, length = qkv.shape
378
+ assert width % (3 * self.n_heads) == 0
379
+ ch = width // (3 * self.n_heads)
380
+ q, k, v = qkv.chunk(3, dim=1)
381
+ scale = 1 / math.sqrt(math.sqrt(ch))
382
+ weight = th.einsum(
383
+ "bct,bcs->bts",
384
+ (q * scale).view(bs * self.n_heads, ch, length),
385
+ (k * scale).view(bs * self.n_heads, ch, length),
386
+ ) # More stable with f16 than dividing afterwards
387
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
388
+ a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
389
+ return a.reshape(bs, -1, length)
390
+
391
+ @staticmethod
392
+ def count_flops(model, _x, y):
393
+ return count_flops_attn(model, _x, y)
394
+
395
+
396
+ class UNetModel(nn.Module):
397
+ """
398
+ The full UNet model with attention and timestep embedding.
399
+
400
+ :param in_channels: channels in the input Tensor.
401
+ :param model_channels: base channel count for the model.
402
+ :param out_channels: channels in the output Tensor.
403
+ :param num_res_blocks: number of residual blocks per downsample.
404
+ :param attention_resolutions: a collection of downsample rates at which
405
+ attention will take place. May be a set, list, or tuple.
406
+ For example, if this contains 4, then at 4x downsampling, attention
407
+ will be used.
408
+ :param dropout: the dropout probability.
409
+ :param channel_mult: channel multiplier for each level of the UNet.
410
+ :param conv_resample: if True, use learned convolutions for upsampling and
411
+ downsampling.
412
+ :param dims: determines if the signal is 1D, 2D, or 3D.
413
+ :param num_classes: if specified (as an int), then this model will be
414
+ class-conditional with `num_classes` classes.
415
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
416
+ :param num_heads: the number of attention heads in each attention layer.
417
+ :param num_heads_channels: if specified, ignore num_heads and instead use
418
+ a fixed channel width per attention head.
419
+ :param num_heads_upsample: works with num_heads to set a different number
420
+ of heads for upsampling. Deprecated.
421
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
422
+ :param resblock_updown: use residual blocks for up/downsampling.
423
+ :param use_new_attention_order: use a different attention pattern for potentially
424
+ increased efficiency.
425
+ """
426
+
427
+ def __init__(
428
+ self,
429
+ image_size,
430
+ in_channels,
431
+ model_channels,
432
+ out_channels,
433
+ num_res_blocks,
434
+ attention_resolutions,
435
+ dropout=0,
436
+ channel_mult=(1, 2, 4, 8),
437
+ conv_resample=True,
438
+ dims=2,
439
+ num_classes=None,
440
+ use_checkpoint=False,
441
+ use_fp16=False,
442
+ num_heads=1,
443
+ num_head_channels=-1,
444
+ num_heads_upsample=-1,
445
+ use_scale_shift_norm=False,
446
+ resblock_updown=False,
447
+ use_new_attention_order=False,
448
+ ):
449
+ super().__init__()
450
+
451
+ if num_heads_upsample == -1:
452
+ num_heads_upsample = num_heads
453
+
454
+ self.image_size = image_size
455
+ self.in_channels = in_channels
456
+ self.model_channels = model_channels
457
+ self.out_channels = out_channels
458
+ self.num_res_blocks = num_res_blocks
459
+ self.attention_resolutions = attention_resolutions
460
+ self.dropout = dropout
461
+ self.channel_mult = channel_mult
462
+ self.conv_resample = conv_resample
463
+ self.num_classes = num_classes
464
+ self.use_checkpoint = use_checkpoint
465
+ self.dtype = th.float16 if use_fp16 else th.float32
466
+ self.num_heads = num_heads
467
+ self.num_head_channels = num_head_channels
468
+ self.num_heads_upsample = num_heads_upsample
469
+
470
+ time_embed_dim = model_channels * 4
471
+ self.time_embed = nn.Sequential(
472
+ linear(model_channels, time_embed_dim),
473
+ nn.SiLU(),
474
+ linear(time_embed_dim, time_embed_dim),
475
+ )
476
+
477
+ if self.num_classes is not None:
478
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
479
+
480
+ ch = input_ch = int(channel_mult[0] * model_channels)
481
+ self.input_blocks = nn.ModuleList(
482
+ [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
483
+ )
484
+ self._feature_size = ch
485
+ input_block_chans = [ch]
486
+ ds = 1
487
+ for level, mult in enumerate(channel_mult):
488
+ for _ in range(num_res_blocks):
489
+ layers = [
490
+ ResBlock(
491
+ ch,
492
+ time_embed_dim,
493
+ dropout,
494
+ out_channels=int(mult * model_channels),
495
+ dims=dims,
496
+ use_checkpoint=use_checkpoint,
497
+ use_scale_shift_norm=use_scale_shift_norm,
498
+ )
499
+ ]
500
+ ch = int(mult * model_channels)
501
+ if ds in attention_resolutions:
502
+ layers.append(
503
+ AttentionBlock(
504
+ ch,
505
+ use_checkpoint=use_checkpoint,
506
+ num_heads=num_heads,
507
+ num_head_channels=num_head_channels,
508
+ use_new_attention_order=use_new_attention_order,
509
+ )
510
+ )
511
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
512
+ self._feature_size += ch
513
+ input_block_chans.append(ch)
514
+ if level != len(channel_mult) - 1:
515
+ out_ch = ch
516
+ self.input_blocks.append(
517
+ TimestepEmbedSequential(
518
+ ResBlock(
519
+ ch,
520
+ time_embed_dim,
521
+ dropout,
522
+ out_channels=out_ch,
523
+ dims=dims,
524
+ use_checkpoint=use_checkpoint,
525
+ use_scale_shift_norm=use_scale_shift_norm,
526
+ down=True,
527
+ )
528
+ if resblock_updown
529
+ else Downsample(
530
+ ch, conv_resample, dims=dims, out_channels=out_ch
531
+ )
532
+ )
533
+ )
534
+ ch = out_ch
535
+ input_block_chans.append(ch)
536
+ ds *= 2
537
+ self._feature_size += ch
538
+
539
+ self.middle_block = TimestepEmbedSequential(
540
+ ResBlock(
541
+ ch,
542
+ time_embed_dim,
543
+ dropout,
544
+ dims=dims,
545
+ use_checkpoint=use_checkpoint,
546
+ use_scale_shift_norm=use_scale_shift_norm,
547
+ ),
548
+ AttentionBlock(
549
+ ch,
550
+ use_checkpoint=use_checkpoint,
551
+ num_heads=num_heads,
552
+ num_head_channels=num_head_channels,
553
+ use_new_attention_order=use_new_attention_order,
554
+ ),
555
+ ResBlock(
556
+ ch,
557
+ time_embed_dim,
558
+ dropout,
559
+ dims=dims,
560
+ use_checkpoint=use_checkpoint,
561
+ use_scale_shift_norm=use_scale_shift_norm,
562
+ ),
563
+ )
564
+ self._feature_size += ch
565
+
566
+ self.output_blocks = nn.ModuleList([])
567
+ for level, mult in list(enumerate(channel_mult))[::-1]:
568
+ for i in range(num_res_blocks + 1):
569
+ ich = input_block_chans.pop()
570
+ layers = [
571
+ ResBlock(
572
+ ch + ich,
573
+ time_embed_dim,
574
+ dropout,
575
+ out_channels=int(model_channels * mult),
576
+ dims=dims,
577
+ use_checkpoint=use_checkpoint,
578
+ use_scale_shift_norm=use_scale_shift_norm,
579
+ )
580
+ ]
581
+ ch = int(model_channels * mult)
582
+ if ds in attention_resolutions:
583
+ layers.append(
584
+ AttentionBlock(
585
+ ch,
586
+ use_checkpoint=use_checkpoint,
587
+ num_heads=num_heads_upsample,
588
+ num_head_channels=num_head_channels,
589
+ use_new_attention_order=use_new_attention_order,
590
+ )
591
+ )
592
+ if level and i == num_res_blocks:
593
+ out_ch = ch
594
+ layers.append(
595
+ ResBlock(
596
+ ch,
597
+ time_embed_dim,
598
+ dropout,
599
+ out_channels=out_ch,
600
+ dims=dims,
601
+ use_checkpoint=use_checkpoint,
602
+ use_scale_shift_norm=use_scale_shift_norm,
603
+ up=True,
604
+ )
605
+ if resblock_updown
606
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
607
+ )
608
+ ds //= 2
609
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
610
+ self._feature_size += ch
611
+
612
+ self.out = nn.Sequential(
613
+ normalization(ch),
614
+ nn.SiLU(),
615
+ zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
616
+ )
617
+
618
+ def convert_to_fp16(self):
619
+ """
620
+ Convert the torso of the model to float16.
621
+ """
622
+ self.input_blocks.apply(convert_module_to_f16)
623
+ self.middle_block.apply(convert_module_to_f16)
624
+ self.output_blocks.apply(convert_module_to_f16)
625
+
626
+ def convert_to_fp32(self):
627
+ """
628
+ Convert the torso of the model to float32.
629
+ """
630
+ self.input_blocks.apply(convert_module_to_f32)
631
+ self.middle_block.apply(convert_module_to_f32)
632
+ self.output_blocks.apply(convert_module_to_f32)
633
+
634
+ def forward(self, x, timesteps, middle_out=False, y=None):
635
+ """
636
+ Apply the model to an input batch.
637
+
638
+ :param x: an [N x C x ...] Tensor of inputs.
639
+ :param timesteps: a 1-D batch of timesteps.
640
+ :param y: an [N] Tensor of labels, if class-conditional.
641
+ :return: an [N x C x ...] Tensor of outputs.
642
+ """
643
+ #assert (y is not None) == (
644
+ # self.num_classes is not None
645
+ #), "must specify y if and only if the model is class-conditional"
646
+
647
+ hs = []
648
+ emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
649
+
650
+ if self.num_classes is not None:
651
+ try:
652
+ assert y.shape == (x.shape[0],)
653
+ emb = emb + self.label_emb(y)
654
+ except Exception as err:
655
+ print(str(err))
656
+
657
+ h = x.type(self.dtype)
658
+ for module in self.input_blocks:
659
+ h = module(h, emb)
660
+ hs.append(h)
661
+ h = self.middle_block(h, emb)
662
+
663
+ if middle_out:
664
+ middle_out_emb = h.clone()
665
+ else:
666
+ middle_out_emb = None
667
+
668
+ for module in self.output_blocks:
669
+ h = th.cat([h, hs.pop()], dim=1)
670
+ h = module(h, emb)
671
+ h = h.type(x.dtype)
672
+
673
+ if middle_out:
674
+ return self.out(h), middle_out_emb
675
+ else:
676
+ return self.out(h)
677
+
678
+
679
+
680
+ class SuperResModel(UNetModel):
681
+ """
682
+ A UNetModel that performs super-resolution.
683
+
684
+ Expects an extra kwarg `low_res` to condition on a low-resolution image.
685
+ """
686
+
687
+ def __init__(self, image_size, in_channels, *args, **kwargs):
688
+ super().__init__(image_size, in_channels * 2, *args, **kwargs)
689
+
690
+ def forward(self, x, timesteps, low_res=None, **kwargs):
691
+ _, _, new_height, new_width = x.shape
692
+ upsampled = F.interpolate(low_res, (new_height, new_width), mode="bilinear")
693
+ x = th.cat([x, upsampled], dim=1)
694
+ return super().forward(x, timesteps, **kwargs)
695
+
696
+
697
+ class EncoderUNetModel(nn.Module):
698
+ """
699
+ The half UNet model with attention and timestep embedding.
700
+
701
+ For usage, see UNet.
702
+ """
703
+
704
+ def __init__(
705
+ self,
706
+ image_size,
707
+ in_channels,
708
+ model_channels,
709
+ out_channels,
710
+ num_res_blocks,
711
+ attention_resolutions,
712
+ dropout=0,
713
+ channel_mult=(1, 2, 4, 8),
714
+ conv_resample=True,
715
+ dims=2,
716
+ use_checkpoint=False,
717
+ use_fp16=False,
718
+ num_heads=1,
719
+ num_head_channels=-1,
720
+ num_heads_upsample=-1,
721
+ use_scale_shift_norm=False,
722
+ resblock_updown=False,
723
+ use_new_attention_order=False,
724
+ pool="adaptive",
725
+ ):
726
+ super().__init__()
727
+
728
+ if num_heads_upsample == -1:
729
+ num_heads_upsample = num_heads
730
+
731
+ self.in_channels = in_channels
732
+ self.model_channels = model_channels
733
+ self.out_channels = out_channels
734
+ self.num_res_blocks = num_res_blocks
735
+ self.attention_resolutions = attention_resolutions
736
+ self.dropout = dropout
737
+ self.channel_mult = channel_mult
738
+ self.conv_resample = conv_resample
739
+ self.use_checkpoint = use_checkpoint
740
+ self.dtype = th.float16 if use_fp16 else th.float32
741
+ self.num_heads = num_heads
742
+ self.num_head_channels = num_head_channels
743
+ self.num_heads_upsample = num_heads_upsample
744
+
745
+ time_embed_dim = model_channels * 4
746
+ self.time_embed = nn.Sequential(
747
+ linear(model_channels, time_embed_dim),
748
+ nn.SiLU(),
749
+ linear(time_embed_dim, time_embed_dim),
750
+ )
751
+
752
+ ch = int(channel_mult[0] * model_channels)
753
+ self.input_blocks = nn.ModuleList(
754
+ [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
755
+ )
756
+ self._feature_size = ch
757
+ input_block_chans = [ch]
758
+ ds = 1
759
+ for level, mult in enumerate(channel_mult):
760
+ for _ in range(num_res_blocks):
761
+ layers = [
762
+ ResBlock(
763
+ ch,
764
+ time_embed_dim,
765
+ dropout,
766
+ out_channels=int(mult * model_channels),
767
+ dims=dims,
768
+ use_checkpoint=use_checkpoint,
769
+ use_scale_shift_norm=use_scale_shift_norm,
770
+ )
771
+ ]
772
+ ch = int(mult * model_channels)
773
+ if ds in attention_resolutions:
774
+ layers.append(
775
+ AttentionBlock(
776
+ ch,
777
+ use_checkpoint=use_checkpoint,
778
+ num_heads=num_heads,
779
+ num_head_channels=num_head_channels,
780
+ use_new_attention_order=use_new_attention_order,
781
+ )
782
+ )
783
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
784
+ self._feature_size += ch
785
+ input_block_chans.append(ch)
786
+ if level != len(channel_mult) - 1:
787
+ out_ch = ch
788
+ self.input_blocks.append(
789
+ TimestepEmbedSequential(
790
+ ResBlock(
791
+ ch,
792
+ time_embed_dim,
793
+ dropout,
794
+ out_channels=out_ch,
795
+ dims=dims,
796
+ use_checkpoint=use_checkpoint,
797
+ use_scale_shift_norm=use_scale_shift_norm,
798
+ down=True,
799
+ )
800
+ if resblock_updown
801
+ else Downsample(
802
+ ch, conv_resample, dims=dims, out_channels=out_ch
803
+ )
804
+ )
805
+ )
806
+ ch = out_ch
807
+ input_block_chans.append(ch)
808
+ ds *= 2
809
+ self._feature_size += ch
810
+
811
+ self.middle_block = TimestepEmbedSequential(
812
+ ResBlock(
813
+ ch,
814
+ time_embed_dim,
815
+ dropout,
816
+ dims=dims,
817
+ use_checkpoint=use_checkpoint,
818
+ use_scale_shift_norm=use_scale_shift_norm,
819
+ ),
820
+ AttentionBlock(
821
+ ch,
822
+ use_checkpoint=use_checkpoint,
823
+ num_heads=num_heads,
824
+ num_head_channels=num_head_channels,
825
+ use_new_attention_order=use_new_attention_order,
826
+ ),
827
+ ResBlock(
828
+ ch,
829
+ time_embed_dim,
830
+ dropout,
831
+ dims=dims,
832
+ use_checkpoint=use_checkpoint,
833
+ use_scale_shift_norm=use_scale_shift_norm,
834
+ ),
835
+ )
836
+ self._feature_size += ch
837
+ self.pool = pool
838
+ if pool == "adaptive":
839
+ self.out = nn.Sequential(
840
+ normalization(ch),
841
+ nn.SiLU(),
842
+ nn.AdaptiveAvgPool2d((1, 1)),
843
+ zero_module(conv_nd(dims, ch, out_channels, 1)),
844
+ nn.Flatten(),
845
+ )
846
+ elif pool == "attention":
847
+ assert num_head_channels != -1
848
+ self.out = nn.Sequential(
849
+ normalization(ch),
850
+ nn.SiLU(),
851
+ AttentionPool2d(
852
+ (image_size // ds), ch, num_head_channels, out_channels
853
+ ),
854
+ )
855
+ elif pool == "spatial":
856
+ self.out = nn.Sequential(
857
+ nn.Linear(self._feature_size, 2048),
858
+ nn.ReLU(),
859
+ nn.Linear(2048, self.out_channels),
860
+ )
861
+ elif pool == "spatial_v2":
862
+ self.out = nn.Sequential(
863
+ nn.Linear(self._feature_size, 2048),
864
+ normalization(2048),
865
+ nn.SiLU(),
866
+ nn.Linear(2048, self.out_channels),
867
+ )
868
+ else:
869
+ raise NotImplementedError(f"Unexpected {pool} pooling")
870
+
871
+ def convert_to_fp16(self):
872
+ """
873
+ Convert the torso of the model to float16.
874
+ """
875
+ self.input_blocks.apply(convert_module_to_f16)
876
+ self.middle_block.apply(convert_module_to_f16)
877
+
878
+ def convert_to_fp32(self):
879
+ """
880
+ Convert the torso of the model to float32.
881
+ """
882
+ self.input_blocks.apply(convert_module_to_f32)
883
+ self.middle_block.apply(convert_module_to_f32)
884
+
885
+ def forward(self, x, timesteps):
886
+ """
887
+ Apply the model to an input batch.
888
+
889
+ :param x: an [N x C x ...] Tensor of inputs.
890
+ :param timesteps: a 1-D batch of timesteps.
891
+ :return: an [N x K] Tensor of outputs.
892
+ """
893
+ emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
894
+
895
+ results = []
896
+ h = x.type(self.dtype)
897
+ for module in self.input_blocks:
898
+ h = module(h, emb)
899
+ if self.pool.startswith("spatial"):
900
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
901
+ h = self.middle_block(h, emb)
902
+ if self.pool.startswith("spatial"):
903
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
904
+ h = th.cat(results, axis=-1)
905
+ return self.out(h)
906
+ else:
907
+ h = h.type(x.dtype)
908
+ return self.out(h)
guided_diffusion/model-card.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Overview
2
+
3
+ These are diffusion models and noised image classifiers described in the paper [Diffusion Models Beat GANs on Image Synthesis](https://arxiv.org/abs/2105.05233).
4
+ Included in this release are the following models:
5
+
6
+ * Noisy ImageNet classifiers at resolutions 64x64, 128x128, 256x256, 512x512
7
+ * A class-unconditional ImageNet diffusion model at resolution 256x256
8
+ * Class conditional ImageNet diffusion models at 64x64, 128x128, 256x256, 512x512 resolutions
9
+ * Class-conditional ImageNet upsampling diffusion models: 64x64->256x256, 128x128->512x512
10
+ * Diffusion models trained on three LSUN classes at 256x256 resolution: cat, horse, bedroom
11
+
12
+ # Datasets
13
+
14
+ All of the models we are releasing were either trained on the [ILSVRC 2012 subset of ImageNet](http://www.image-net.org/challenges/LSVRC/2012/) or on single classes of [LSUN](https://arxiv.org/abs/1506.03365).
15
+ Here, we describe characteristics of these datasets which impact model behavior:
16
+
17
+ **LSUN**: This dataset was collected in 2015 using a combination of human labeling (from Amazon Mechanical Turk) and automated data labeling.
18
+ * Each of the three classes we consider contain over a million images.
19
+ * The dataset creators found that the label accuracy was roughly 90% across the entire LSUN dataset when measured by trained experts.
20
+ * Images are scraped from the internet, and LSUN cat images in particular tend to often follow a “meme” format.
21
+ * We found that there are occasionally humans in these photos, including faces, especially within the cat class.
22
+
23
+ **ILSVRC 2012 subset of ImageNet**: This dataset was curated in 2012 and consists of roughly one million images, each belonging to one of 1000 classes.
24
+ * A large portion of the classes in this dataset are animals, plants, and other naturally-occurring objects.
25
+ * Many images contain humans, although usually these humans aren’t reflected by the class label (e.g. the class “Tench, tinca tinca” contains many photos of people holding fish).
26
+
27
+ # Performance
28
+
29
+ These models are intended to generate samples consistent with their training distributions.
30
+ This has been measured in terms of FID, Precision, and Recall.
31
+ These metrics all rely on the representations of a [pre-trained Inception-V3 model](https://arxiv.org/abs/1512.00567),
32
+ which was trained on ImageNet, and so is likely to focus more on the ImageNet classes (such as animals) than on other visual features (such as human faces).
33
+
34
+ Qualitatively, the samples produced by these models often look highly realistic, especially when a diffusion model is combined with a noisy classifier.
35
+
36
+ # Intended Use
37
+
38
+ These models are intended to be used for research purposes only.
39
+ In particular, they can be used as a baseline for generative modeling research, or as a starting point to build off of for such research.
40
+
41
+ These models are not intended to be commercially deployed.
42
+ Additionally, they are not intended to be used to create propaganda or offensive imagery.
43
+
44
+ Before releasing these models, we probed their ability to ease the creation of targeted imagery, since doing so could be potentially harmful.
45
+ We did this either by fine-tuning our ImageNet models on a target LSUN class, or through classifier guidance with publicly available [CLIP models](https://github.com/openai/CLIP).
46
+ * To probe fine-tuning capabilities, we restricted our compute budget to roughly $100 and tried both standard fine-tuning,
47
+ and a diffusion-specific approach where we train a specialized classifier for the LSUN class. The resulting FIDs were significantly worse than publicly available GAN models, indicating that fine-tuning an ImageNet diffusion model does not significantly lower the cost of image generation.
48
+ * To probe guidance with CLIP, we tried two approaches for using pre-trained CLIP models for classifier guidance. Either we fed the noised image to CLIP directly and used its gradients, or we fed the diffusion model's denoised prediction to the CLIP model and differentiated through the whole process. In both cases, we found that it was difficult to recover information from the CLIP model, indicating that these diffusion models are unlikely to make it significantly easier to extract knowledge from CLIP compared to existing GAN models.
49
+
50
+ # Limitations
51
+
52
+ These models sometimes produce highly unrealistic outputs, particularly when generating images containing human faces.
53
+ This may stem from ImageNet's emphasis on non-human objects.
54
+
55
+ While classifier guidance can improve sample quality, it reduces diversity, resulting in some modes of the data distribution being underrepresented.
56
+ This can potentially amplify existing biases in the training dataset such as gender and racial biases.
57
+
58
+ Because ImageNet and LSUN contain images from the internet, they include photos of real people, and the model may have memorized some of the information contained in these photos.
59
+ However, these images are already publicly available, and existing generative models trained on ImageNet have not demonstrated significant leakage of this information.
guided_diffusion/scripts/classifier_sample.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Like image_sample.py, but use a noisy image classifier to guide the sampling
3
+ process towards more realistic images.
4
+ """
5
+
6
+ import argparse
7
+ import os
8
+
9
+ import numpy as np
10
+ import torch as th
11
+ import torch.distributed as dist
12
+ import torch.nn.functional as F
13
+
14
+ from guided_diffusion import dist_util, logger
15
+ from guided_diffusion.script_util import (
16
+ NUM_CLASSES,
17
+ model_and_diffusion_defaults,
18
+ classifier_defaults,
19
+ create_model_and_diffusion,
20
+ create_classifier,
21
+ add_dict_to_argparser,
22
+ args_to_dict,
23
+ )
24
+
25
+
26
+ def main():
27
+ args = create_argparser().parse_args()
28
+
29
+ dist_util.setup_dist()
30
+ logger.configure()
31
+
32
+ logger.log("creating model and diffusion...")
33
+ model, diffusion = create_model_and_diffusion(
34
+ **args_to_dict(args, model_and_diffusion_defaults().keys())
35
+ )
36
+ model.load_state_dict(
37
+ dist_util.load_state_dict(args.model_path, map_location="cpu")
38
+ )
39
+ model.to(dist_util.dev())
40
+ if args.use_fp16:
41
+ model.convert_to_fp16()
42
+ model.eval()
43
+
44
+ logger.log("loading classifier...")
45
+ classifier = create_classifier(**args_to_dict(args, classifier_defaults().keys()))
46
+ classifier.load_state_dict(
47
+ dist_util.load_state_dict(args.classifier_path, map_location="cpu")
48
+ )
49
+ classifier.to(dist_util.dev())
50
+ if args.classifier_use_fp16:
51
+ classifier.convert_to_fp16()
52
+ classifier.eval()
53
+
54
+ def cond_fn(x, t, y=None):
55
+ assert y is not None
56
+ with th.enable_grad():
57
+ x_in = x.detach().requires_grad_(True)
58
+ logits = classifier(x_in, t)
59
+ log_probs = F.log_softmax(logits, dim=-1)
60
+ selected = log_probs[range(len(logits)), y.view(-1)]
61
+ return th.autograd.grad(selected.sum(), x_in)[0] * args.classifier_scale
62
+
63
+ def model_fn(x, t, y=None):
64
+ assert y is not None
65
+ return model(x, t, y if args.class_cond else None)
66
+
67
+ logger.log("sampling...")
68
+ all_images = []
69
+ all_labels = []
70
+ while len(all_images) * args.batch_size < args.num_samples:
71
+ model_kwargs = {}
72
+ classes = th.randint(
73
+ low=0, high=NUM_CLASSES, size=(args.batch_size,), device=dist_util.dev()
74
+ )
75
+ model_kwargs["y"] = classes
76
+ sample_fn = (
77
+ diffusion.p_sample_loop if not args.use_ddim else diffusion.ddim_sample_loop
78
+ )
79
+ sample = sample_fn(
80
+ model_fn,
81
+ (args.batch_size, 3, args.image_size, args.image_size),
82
+ clip_denoised=args.clip_denoised,
83
+ model_kwargs=model_kwargs,
84
+ cond_fn=cond_fn,
85
+ device=dist_util.dev(),
86
+ )
87
+ sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)
88
+ sample = sample.permute(0, 2, 3, 1)
89
+ sample = sample.contiguous()
90
+
91
+ gathered_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())]
92
+ dist.all_gather(gathered_samples, sample) # gather not supported with NCCL
93
+ all_images.extend([sample.cpu().numpy() for sample in gathered_samples])
94
+ gathered_labels = [th.zeros_like(classes) for _ in range(dist.get_world_size())]
95
+ dist.all_gather(gathered_labels, classes)
96
+ all_labels.extend([labels.cpu().numpy() for labels in gathered_labels])
97
+ logger.log(f"created {len(all_images) * args.batch_size} samples")
98
+
99
+ arr = np.concatenate(all_images, axis=0)
100
+ arr = arr[: args.num_samples]
101
+ label_arr = np.concatenate(all_labels, axis=0)
102
+ label_arr = label_arr[: args.num_samples]
103
+ if dist.get_rank() == 0:
104
+ shape_str = "x".join([str(x) for x in arr.shape])
105
+ out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz")
106
+ logger.log(f"saving to {out_path}")
107
+ np.savez(out_path, arr, label_arr)
108
+
109
+ dist.barrier()
110
+ logger.log("sampling complete")
111
+
112
+
113
+ def create_argparser():
114
+ defaults = dict(
115
+ clip_denoised=True,
116
+ num_samples=10000,
117
+ batch_size=16,
118
+ use_ddim=False,
119
+ model_path="",
120
+ classifier_path="",
121
+ classifier_scale=1.0,
122
+ )
123
+ defaults.update(model_and_diffusion_defaults())
124
+ defaults.update(classifier_defaults())
125
+ parser = argparse.ArgumentParser()
126
+ add_dict_to_argparser(parser, defaults)
127
+ return parser
128
+
129
+
130
+ if __name__ == "__main__":
131
+ main()
guided_diffusion/scripts/classifier_train.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Train a noised image classifier on ImageNet.
3
+ """
4
+
5
+ import argparse
6
+ import os
7
+
8
+ import blobfile as bf
9
+ import torch as th
10
+ import torch.distributed as dist
11
+ import torch.nn.functional as F
12
+ from torch.nn.parallel.distributed import DistributedDataParallel as DDP
13
+ from torch.optim import AdamW
14
+
15
+ from guided_diffusion import dist_util, logger
16
+ from guided_diffusion.fp16_util import MixedPrecisionTrainer
17
+ from guided_diffusion.image_datasets import load_data
18
+ from guided_diffusion.resample import create_named_schedule_sampler
19
+ from guided_diffusion.script_util import (
20
+ add_dict_to_argparser,
21
+ args_to_dict,
22
+ classifier_and_diffusion_defaults,
23
+ create_classifier_and_diffusion,
24
+ )
25
+ from guided_diffusion.train_util import parse_resume_step_from_filename, log_loss_dict
26
+
27
+
28
+ def main():
29
+ args = create_argparser().parse_args()
30
+
31
+ dist_util.setup_dist()
32
+ logger.configure()
33
+
34
+ logger.log("creating model and diffusion...")
35
+ model, diffusion = create_classifier_and_diffusion(
36
+ **args_to_dict(args, classifier_and_diffusion_defaults().keys())
37
+ )
38
+ model.to(dist_util.dev())
39
+ if args.noised:
40
+ schedule_sampler = create_named_schedule_sampler(
41
+ args.schedule_sampler, diffusion
42
+ )
43
+
44
+ resume_step = 0
45
+ if args.resume_checkpoint:
46
+ resume_step = parse_resume_step_from_filename(args.resume_checkpoint)
47
+ if dist.get_rank() == 0:
48
+ logger.log(
49
+ f"loading model from checkpoint: {args.resume_checkpoint}... at {resume_step} step"
50
+ )
51
+ model.load_state_dict(
52
+ dist_util.load_state_dict(
53
+ args.resume_checkpoint, map_location=dist_util.dev()
54
+ )
55
+ )
56
+
57
+ # Needed for creating correct EMAs and fp16 parameters.
58
+ dist_util.sync_params(model.parameters())
59
+
60
+ mp_trainer = MixedPrecisionTrainer(
61
+ model=model, use_fp16=args.classifier_use_fp16, initial_lg_loss_scale=16.0
62
+ )
63
+
64
+ model = DDP(
65
+ model,
66
+ device_ids=[dist_util.dev()],
67
+ output_device=dist_util.dev(),
68
+ broadcast_buffers=False,
69
+ bucket_cap_mb=128,
70
+ find_unused_parameters=False,
71
+ )
72
+
73
+ logger.log("creating data loader...")
74
+ data = load_data(
75
+ data_dir=args.data_dir,
76
+ batch_size=args.batch_size,
77
+ image_size=args.image_size,
78
+ class_cond=True,
79
+ random_crop=True,
80
+ )
81
+ if args.val_data_dir:
82
+ val_data = load_data(
83
+ data_dir=args.val_data_dir,
84
+ batch_size=args.batch_size,
85
+ image_size=args.image_size,
86
+ class_cond=True,
87
+ )
88
+ else:
89
+ val_data = None
90
+
91
+ logger.log(f"creating optimizer...")
92
+ opt = AdamW(mp_trainer.master_params, lr=args.lr, weight_decay=args.weight_decay)
93
+ if args.resume_checkpoint:
94
+ opt_checkpoint = bf.join(
95
+ bf.dirname(args.resume_checkpoint), f"opt{resume_step:06}.pt"
96
+ )
97
+ logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}")
98
+ opt.load_state_dict(
99
+ dist_util.load_state_dict(opt_checkpoint, map_location=dist_util.dev())
100
+ )
101
+
102
+ logger.log("training classifier model...")
103
+
104
+ def forward_backward_log(data_loader, prefix="train"):
105
+ batch, extra = next(data_loader)
106
+ labels = extra["y"].to(dist_util.dev())
107
+
108
+ batch = batch.to(dist_util.dev())
109
+ # Noisy images
110
+ if args.noised:
111
+ t, _ = schedule_sampler.sample(batch.shape[0], dist_util.dev())
112
+ batch = diffusion.q_sample(batch, t)
113
+ else:
114
+ t = th.zeros(batch.shape[0], dtype=th.long, device=dist_util.dev())
115
+
116
+ for i, (sub_batch, sub_labels, sub_t) in enumerate(
117
+ split_microbatches(args.microbatch, batch, labels, t)
118
+ ):
119
+ logits = model(sub_batch, timesteps=sub_t)
120
+ loss = F.cross_entropy(logits, sub_labels, reduction="none")
121
+
122
+ losses = {}
123
+ losses[f"{prefix}_loss"] = loss.detach()
124
+ losses[f"{prefix}_acc@1"] = compute_top_k(
125
+ logits, sub_labels, k=1, reduction="none"
126
+ )
127
+ losses[f"{prefix}_acc@5"] = compute_top_k(
128
+ logits, sub_labels, k=5, reduction="none"
129
+ )
130
+ log_loss_dict(diffusion, sub_t, losses)
131
+ del losses
132
+ loss = loss.mean()
133
+ if loss.requires_grad:
134
+ if i == 0:
135
+ mp_trainer.zero_grad()
136
+ mp_trainer.backward(loss * len(sub_batch) / len(batch))
137
+
138
+ for step in range(args.iterations - resume_step):
139
+ logger.logkv("step", step + resume_step)
140
+ logger.logkv(
141
+ "samples",
142
+ (step + resume_step + 1) * args.batch_size * dist.get_world_size(),
143
+ )
144
+ if args.anneal_lr:
145
+ set_annealed_lr(opt, args.lr, (step + resume_step) / args.iterations)
146
+ forward_backward_log(data)
147
+ mp_trainer.optimize(opt)
148
+ if val_data is not None and not step % args.eval_interval:
149
+ with th.no_grad():
150
+ with model.no_sync():
151
+ model.eval()
152
+ forward_backward_log(val_data, prefix="val")
153
+ model.train()
154
+ if not step % args.log_interval:
155
+ logger.dumpkvs()
156
+ if (
157
+ step
158
+ and dist.get_rank() == 0
159
+ and not (step + resume_step) % args.save_interval
160
+ ):
161
+ logger.log("saving model...")
162
+ save_model(mp_trainer, opt, step + resume_step)
163
+
164
+ if dist.get_rank() == 0:
165
+ logger.log("saving model...")
166
+ save_model(mp_trainer, opt, step + resume_step)
167
+ dist.barrier()
168
+
169
+
170
+ def set_annealed_lr(opt, base_lr, frac_done):
171
+ lr = base_lr * (1 - frac_done)
172
+ for param_group in opt.param_groups:
173
+ param_group["lr"] = lr
174
+
175
+
176
+ def save_model(mp_trainer, opt, step):
177
+ if dist.get_rank() == 0:
178
+ th.save(
179
+ mp_trainer.master_params_to_state_dict(mp_trainer.master_params),
180
+ os.path.join(logger.get_dir(), f"model{step:06d}.pt"),
181
+ )
182
+ th.save(opt.state_dict(), os.path.join(logger.get_dir(), f"opt{step:06d}.pt"))
183
+
184
+
185
+ def compute_top_k(logits, labels, k, reduction="mean"):
186
+ _, top_ks = th.topk(logits, k, dim=-1)
187
+ if reduction == "mean":
188
+ return (top_ks == labels[:, None]).float().sum(dim=-1).mean().item()
189
+ elif reduction == "none":
190
+ return (top_ks == labels[:, None]).float().sum(dim=-1)
191
+
192
+
193
+ def split_microbatches(microbatch, *args):
194
+ bs = len(args[0])
195
+ if microbatch == -1 or microbatch >= bs:
196
+ yield tuple(args)
197
+ else:
198
+ for i in range(0, bs, microbatch):
199
+ yield tuple(x[i : i + microbatch] if x is not None else None for x in args)
200
+
201
+
202
+ def create_argparser():
203
+ defaults = dict(
204
+ data_dir="",
205
+ val_data_dir="",
206
+ noised=True,
207
+ iterations=150000,
208
+ lr=3e-4,
209
+ weight_decay=0.0,
210
+ anneal_lr=False,
211
+ batch_size=4,
212
+ microbatch=-1,
213
+ schedule_sampler="uniform",
214
+ resume_checkpoint="",
215
+ log_interval=10,
216
+ eval_interval=5,
217
+ save_interval=10000,
218
+ )
219
+ defaults.update(classifier_and_diffusion_defaults())
220
+ parser = argparse.ArgumentParser()
221
+ add_dict_to_argparser(parser, defaults)
222
+ return parser
223
+
224
+
225
+ if __name__ == "__main__":
226
+ main()
guided_diffusion/scripts/image_nll.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Approximate the bits/dimension for an image model.
3
+ """
4
+
5
+ import argparse
6
+ import os
7
+
8
+ import numpy as np
9
+ import torch.distributed as dist
10
+
11
+ from guided_diffusion import dist_util, logger
12
+ from guided_diffusion.image_datasets import load_data
13
+ from guided_diffusion.script_util import (
14
+ model_and_diffusion_defaults,
15
+ create_model_and_diffusion,
16
+ add_dict_to_argparser,
17
+ args_to_dict,
18
+ )
19
+
20
+
21
+ def main():
22
+ args = create_argparser().parse_args()
23
+
24
+ dist_util.setup_dist()
25
+ logger.configure()
26
+
27
+ logger.log("creating model and diffusion...")
28
+ model, diffusion = create_model_and_diffusion(
29
+ **args_to_dict(args, model_and_diffusion_defaults().keys())
30
+ )
31
+ model.load_state_dict(
32
+ dist_util.load_state_dict(args.model_path, map_location="cpu")
33
+ )
34
+ model.to(dist_util.dev())
35
+ model.eval()
36
+
37
+ logger.log("creating data loader...")
38
+ data = load_data(
39
+ data_dir=args.data_dir,
40
+ batch_size=args.batch_size,
41
+ image_size=args.image_size,
42
+ class_cond=args.class_cond,
43
+ deterministic=True,
44
+ )
45
+
46
+ logger.log("evaluating...")
47
+ run_bpd_evaluation(model, diffusion, data, args.num_samples, args.clip_denoised)
48
+
49
+
50
+ def run_bpd_evaluation(model, diffusion, data, num_samples, clip_denoised):
51
+ all_bpd = []
52
+ all_metrics = {"vb": [], "mse": [], "xstart_mse": []}
53
+ num_complete = 0
54
+ while num_complete < num_samples:
55
+ batch, model_kwargs = next(data)
56
+ batch = batch.to(dist_util.dev())
57
+ model_kwargs = {k: v.to(dist_util.dev()) for k, v in model_kwargs.items()}
58
+ minibatch_metrics = diffusion.calc_bpd_loop(
59
+ model, batch, clip_denoised=clip_denoised, model_kwargs=model_kwargs
60
+ )
61
+
62
+ for key, term_list in all_metrics.items():
63
+ terms = minibatch_metrics[key].mean(dim=0) / dist.get_world_size()
64
+ dist.all_reduce(terms)
65
+ term_list.append(terms.detach().cpu().numpy())
66
+
67
+ total_bpd = minibatch_metrics["total_bpd"]
68
+ total_bpd = total_bpd.mean() / dist.get_world_size()
69
+ dist.all_reduce(total_bpd)
70
+ all_bpd.append(total_bpd.item())
71
+ num_complete += dist.get_world_size() * batch.shape[0]
72
+
73
+ logger.log(f"done {num_complete} samples: bpd={np.mean(all_bpd)}")
74
+
75
+ if dist.get_rank() == 0:
76
+ for name, terms in all_metrics.items():
77
+ out_path = os.path.join(logger.get_dir(), f"{name}_terms.npz")
78
+ logger.log(f"saving {name} terms to {out_path}")
79
+ np.savez(out_path, np.mean(np.stack(terms), axis=0))
80
+
81
+ dist.barrier()
82
+ logger.log("evaluation complete")
83
+
84
+
85
+ def create_argparser():
86
+ defaults = dict(
87
+ data_dir="", clip_denoised=True, num_samples=1000, batch_size=1, model_path=""
88
+ )
89
+ defaults.update(model_and_diffusion_defaults())
90
+ parser = argparse.ArgumentParser()
91
+ add_dict_to_argparser(parser, defaults)
92
+ return parser
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
guided_diffusion/scripts/image_sample.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generate a large batch of image samples from a model and save them as a large
3
+ numpy array. This can be used to produce samples for FID evaluation.
4
+ """
5
+
6
+ import argparse
7
+ import os
8
+
9
+ import numpy as np
10
+ import torch as th
11
+ import torch.distributed as dist
12
+
13
+ from guided_diffusion import dist_util, logger
14
+ from guided_diffusion.script_util import (
15
+ NUM_CLASSES,
16
+ model_and_diffusion_defaults,
17
+ create_model_and_diffusion,
18
+ add_dict_to_argparser,
19
+ args_to_dict,
20
+ )
21
+
22
+
23
+ def main():
24
+ args = create_argparser().parse_args()
25
+
26
+ dist_util.setup_dist()
27
+ logger.configure()
28
+
29
+ logger.log("creating model and diffusion...")
30
+ model, diffusion = create_model_and_diffusion(
31
+ **args_to_dict(args, model_and_diffusion_defaults().keys())
32
+ )
33
+ model.load_state_dict(
34
+ dist_util.load_state_dict(args.model_path, map_location="cpu")
35
+ )
36
+ model.to(dist_util.dev())
37
+ if args.use_fp16:
38
+ model.convert_to_fp16()
39
+ model.eval()
40
+
41
+ logger.log("sampling...")
42
+ all_images = []
43
+ all_labels = []
44
+ while len(all_images) * args.batch_size < args.num_samples:
45
+ model_kwargs = {}
46
+ if args.class_cond:
47
+ classes = th.randint(
48
+ low=0, high=NUM_CLASSES, size=(args.batch_size,), device=dist_util.dev()
49
+ )
50
+ model_kwargs["y"] = classes
51
+ sample_fn = (
52
+ diffusion.p_sample_loop if not args.use_ddim else diffusion.ddim_sample_loop
53
+ )
54
+ sample = sample_fn(
55
+ model,
56
+ (args.batch_size, 3, args.image_size, args.image_size),
57
+ clip_denoised=args.clip_denoised,
58
+ model_kwargs=model_kwargs,
59
+ )
60
+ sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)
61
+ sample = sample.permute(0, 2, 3, 1)
62
+ sample = sample.contiguous()
63
+
64
+ gathered_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())]
65
+ dist.all_gather(gathered_samples, sample) # gather not supported with NCCL
66
+ all_images.extend([sample.cpu().numpy() for sample in gathered_samples])
67
+ if args.class_cond:
68
+ gathered_labels = [
69
+ th.zeros_like(classes) for _ in range(dist.get_world_size())
70
+ ]
71
+ dist.all_gather(gathered_labels, classes)
72
+ all_labels.extend([labels.cpu().numpy() for labels in gathered_labels])
73
+ logger.log(f"created {len(all_images) * args.batch_size} samples")
74
+
75
+ arr = np.concatenate(all_images, axis=0)
76
+ arr = arr[: args.num_samples]
77
+ if args.class_cond:
78
+ label_arr = np.concatenate(all_labels, axis=0)
79
+ label_arr = label_arr[: args.num_samples]
80
+ if dist.get_rank() == 0:
81
+ shape_str = "x".join([str(x) for x in arr.shape])
82
+ out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz")
83
+ logger.log(f"saving to {out_path}")
84
+ if args.class_cond:
85
+ np.savez(out_path, arr, label_arr)
86
+ else:
87
+ np.savez(out_path, arr)
88
+
89
+ dist.barrier()
90
+ logger.log("sampling complete")
91
+
92
+
93
+ def create_argparser():
94
+ defaults = dict(
95
+ clip_denoised=True,
96
+ num_samples=10000,
97
+ batch_size=16,
98
+ use_ddim=False,
99
+ model_path="",
100
+ )
101
+ defaults.update(model_and_diffusion_defaults())
102
+ parser = argparse.ArgumentParser()
103
+ add_dict_to_argparser(parser, defaults)
104
+ return parser
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
guided_diffusion/scripts/image_train.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Train a diffusion model on images.
3
+ """
4
+
5
+ import argparse
6
+
7
+ from guided_diffusion import dist_util, logger
8
+ from guided_diffusion.image_datasets import load_data
9
+ from guided_diffusion.resample import create_named_schedule_sampler
10
+ from guided_diffusion.script_util import (
11
+ model_and_diffusion_defaults,
12
+ create_model_and_diffusion,
13
+ args_to_dict,
14
+ add_dict_to_argparser,
15
+ )
16
+ from guided_diffusion.train_util import TrainLoop
17
+
18
+
19
+ def main():
20
+ args = create_argparser().parse_args()
21
+
22
+ dist_util.setup_dist()
23
+ logger.configure()
24
+
25
+ logger.log("creating model and diffusion...")
26
+ model, diffusion = create_model_and_diffusion(
27
+ **args_to_dict(args, model_and_diffusion_defaults().keys())
28
+ )
29
+ model.to(dist_util.dev())
30
+ schedule_sampler = create_named_schedule_sampler(args.schedule_sampler, diffusion)
31
+
32
+ logger.log("creating data loader...")
33
+ data = load_data(
34
+ data_dir=args.data_dir,
35
+ batch_size=args.batch_size,
36
+ image_size=args.image_size,
37
+ class_cond=args.class_cond,
38
+ )
39
+
40
+ logger.log("training...")
41
+ TrainLoop(
42
+ model=model,
43
+ diffusion=diffusion,
44
+ data=data,
45
+ batch_size=args.batch_size,
46
+ microbatch=args.microbatch,
47
+ lr=args.lr,
48
+ ema_rate=args.ema_rate,
49
+ log_interval=args.log_interval,
50
+ save_interval=args.save_interval,
51
+ resume_checkpoint=args.resume_checkpoint,
52
+ use_fp16=args.use_fp16,
53
+ fp16_scale_growth=args.fp16_scale_growth,
54
+ schedule_sampler=schedule_sampler,
55
+ weight_decay=args.weight_decay,
56
+ lr_anneal_steps=args.lr_anneal_steps,
57
+ ).run_loop()
58
+
59
+
60
+ def create_argparser():
61
+ defaults = dict(
62
+ data_dir="",
63
+ schedule_sampler="uniform",
64
+ lr=1e-4,
65
+ weight_decay=0.0,
66
+ lr_anneal_steps=0,
67
+ batch_size=1,
68
+ microbatch=-1, # -1 disables microbatches
69
+ ema_rate="0.9999", # comma-separated list of EMA values
70
+ log_interval=10,
71
+ save_interval=10000,
72
+ resume_checkpoint="",
73
+ use_fp16=False,
74
+ fp16_scale_growth=1e-3,
75
+ )
76
+ defaults.update(model_and_diffusion_defaults())
77
+ parser = argparse.ArgumentParser()
78
+ add_dict_to_argparser(parser, defaults)
79
+ return parser
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
guided_diffusion/scripts/super_res_sample.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generate a large batch of samples from a super resolution model, given a batch
3
+ of samples from a regular model from image_sample.py.
4
+ """
5
+
6
+ import argparse
7
+ import os
8
+
9
+ import blobfile as bf
10
+ import numpy as np
11
+ import torch as th
12
+ import torch.distributed as dist
13
+
14
+ from guided_diffusion import dist_util, logger
15
+ from guided_diffusion.script_util import (
16
+ sr_model_and_diffusion_defaults,
17
+ sr_create_model_and_diffusion,
18
+ args_to_dict,
19
+ add_dict_to_argparser,
20
+ )
21
+
22
+
23
+ def main():
24
+ args = create_argparser().parse_args()
25
+
26
+ dist_util.setup_dist()
27
+ logger.configure()
28
+
29
+ logger.log("creating model...")
30
+ model, diffusion = sr_create_model_and_diffusion(
31
+ **args_to_dict(args, sr_model_and_diffusion_defaults().keys())
32
+ )
33
+ model.load_state_dict(
34
+ dist_util.load_state_dict(args.model_path, map_location="cpu")
35
+ )
36
+ model.to(dist_util.dev())
37
+ if args.use_fp16:
38
+ model.convert_to_fp16()
39
+ model.eval()
40
+
41
+ logger.log("loading data...")
42
+ data = load_data_for_worker(args.base_samples, args.batch_size, args.class_cond)
43
+
44
+ logger.log("creating samples...")
45
+ all_images = []
46
+ while len(all_images) * args.batch_size < args.num_samples:
47
+ model_kwargs = next(data)
48
+ model_kwargs = {k: v.to(dist_util.dev()) for k, v in model_kwargs.items()}
49
+ sample = diffusion.p_sample_loop(
50
+ model,
51
+ (args.batch_size, 3, args.large_size, args.large_size),
52
+ clip_denoised=args.clip_denoised,
53
+ model_kwargs=model_kwargs,
54
+ )
55
+ sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)
56
+ sample = sample.permute(0, 2, 3, 1)
57
+ sample = sample.contiguous()
58
+
59
+ all_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())]
60
+ dist.all_gather(all_samples, sample) # gather not supported with NCCL
61
+ for sample in all_samples:
62
+ all_images.append(sample.cpu().numpy())
63
+ logger.log(f"created {len(all_images) * args.batch_size} samples")
64
+
65
+ arr = np.concatenate(all_images, axis=0)
66
+ arr = arr[: args.num_samples]
67
+ if dist.get_rank() == 0:
68
+ shape_str = "x".join([str(x) for x in arr.shape])
69
+ out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz")
70
+ logger.log(f"saving to {out_path}")
71
+ np.savez(out_path, arr)
72
+
73
+ dist.barrier()
74
+ logger.log("sampling complete")
75
+
76
+
77
+ def load_data_for_worker(base_samples, batch_size, class_cond):
78
+ with bf.BlobFile(base_samples, "rb") as f:
79
+ obj = np.load(f)
80
+ image_arr = obj["arr_0"]
81
+ if class_cond:
82
+ label_arr = obj["arr_1"]
83
+ rank = dist.get_rank()
84
+ num_ranks = dist.get_world_size()
85
+ buffer = []
86
+ label_buffer = []
87
+ while True:
88
+ for i in range(rank, len(image_arr), num_ranks):
89
+ buffer.append(image_arr[i])
90
+ if class_cond:
91
+ label_buffer.append(label_arr[i])
92
+ if len(buffer) == batch_size:
93
+ batch = th.from_numpy(np.stack(buffer)).float()
94
+ batch = batch / 127.5 - 1.0
95
+ batch = batch.permute(0, 3, 1, 2)
96
+ res = dict(low_res=batch)
97
+ if class_cond:
98
+ res["y"] = th.from_numpy(np.stack(label_buffer))
99
+ yield res
100
+ buffer, label_buffer = [], []
101
+
102
+
103
+ def create_argparser():
104
+ defaults = dict(
105
+ clip_denoised=True,
106
+ num_samples=10000,
107
+ batch_size=16,
108
+ use_ddim=False,
109
+ base_samples="",
110
+ model_path="",
111
+ )
112
+ defaults.update(sr_model_and_diffusion_defaults())
113
+ parser = argparse.ArgumentParser()
114
+ add_dict_to_argparser(parser, defaults)
115
+ return parser
116
+
117
+
118
+ if __name__ == "__main__":
119
+ main()
guided_diffusion/scripts/super_res_train.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Train a super-resolution model.
3
+ """
4
+
5
+ import argparse
6
+
7
+ import torch.nn.functional as F
8
+
9
+ from guided_diffusion import dist_util, logger
10
+ from guided_diffusion.image_datasets import load_data
11
+ from guided_diffusion.resample import create_named_schedule_sampler
12
+ from guided_diffusion.script_util import (
13
+ sr_model_and_diffusion_defaults,
14
+ sr_create_model_and_diffusion,
15
+ args_to_dict,
16
+ add_dict_to_argparser,
17
+ )
18
+ from guided_diffusion.train_util import TrainLoop
19
+
20
+
21
+ def main():
22
+ args = create_argparser().parse_args()
23
+
24
+ dist_util.setup_dist()
25
+ logger.configure()
26
+
27
+ logger.log("creating model...")
28
+ model, diffusion = sr_create_model_and_diffusion(
29
+ **args_to_dict(args, sr_model_and_diffusion_defaults().keys())
30
+ )
31
+ model.to(dist_util.dev())
32
+ schedule_sampler = create_named_schedule_sampler(args.schedule_sampler, diffusion)
33
+
34
+ logger.log("creating data loader...")
35
+ data = load_superres_data(
36
+ args.data_dir,
37
+ args.batch_size,
38
+ large_size=args.large_size,
39
+ small_size=args.small_size,
40
+ class_cond=args.class_cond,
41
+ )
42
+
43
+ logger.log("training...")
44
+ TrainLoop(
45
+ model=model,
46
+ diffusion=diffusion,
47
+ data=data,
48
+ batch_size=args.batch_size,
49
+ microbatch=args.microbatch,
50
+ lr=args.lr,
51
+ ema_rate=args.ema_rate,
52
+ log_interval=args.log_interval,
53
+ save_interval=args.save_interval,
54
+ resume_checkpoint=args.resume_checkpoint,
55
+ use_fp16=args.use_fp16,
56
+ fp16_scale_growth=args.fp16_scale_growth,
57
+ schedule_sampler=schedule_sampler,
58
+ weight_decay=args.weight_decay,
59
+ lr_anneal_steps=args.lr_anneal_steps,
60
+ ).run_loop()
61
+
62
+
63
+ def load_superres_data(data_dir, batch_size, large_size, small_size, class_cond=False):
64
+ data = load_data(
65
+ data_dir=data_dir,
66
+ batch_size=batch_size,
67
+ image_size=large_size,
68
+ class_cond=class_cond,
69
+ )
70
+ for large_batch, model_kwargs in data:
71
+ model_kwargs["low_res"] = F.interpolate(large_batch, small_size, mode="area")
72
+ yield large_batch, model_kwargs
73
+
74
+
75
+ def create_argparser():
76
+ defaults = dict(
77
+ data_dir="",
78
+ schedule_sampler="uniform",
79
+ lr=1e-4,
80
+ weight_decay=0.0,
81
+ lr_anneal_steps=0,
82
+ batch_size=1,
83
+ microbatch=-1,
84
+ ema_rate="0.9999",
85
+ log_interval=10,
86
+ save_interval=10000,
87
+ resume_checkpoint="",
88
+ use_fp16=False,
89
+ fp16_scale_growth=1e-3,
90
+ )
91
+ defaults.update(sr_model_and_diffusion_defaults())
92
+ parser = argparse.ArgumentParser()
93
+ add_dict_to_argparser(parser, defaults)
94
+ return parser
95
+
96
+
97
+ if __name__ == "__main__":
98
+ main()
guided_diffusion/setup.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from setuptools import setup
2
+
3
+ setup(
4
+ name="guided-diffusion",
5
+ py_modules=["guided_diffusion"],
6
+ install_requires=["blobfile>=1.0.5", "torch", "tqdm"],
7
+ )
main.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from optimization.image_editor import ImageEditor
2
+ from optimization.arguments import get_arguments
3
+
4
+
5
+ if __name__ == "__main__":
6
+ args = get_arguments()
7
+ image_editor = ImageEditor(args)
8
+ image_editor.edit_image_by_prompt()
9
+ # image_editor.reconstruct_image()
resizer.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This code was taken from: https://github.com/assafshocher/resizer by Assaf Shocher
2
+ import numpy as np
3
+ import torch
4
+ from math import pi
5
+ from torch import nn
6
+
7
+
8
+ class Resizer(nn.Module):
9
+ def __init__(self, in_shape, scale_factor=None, output_shape=None, kernel=None, antialiasing=True):
10
+ super(Resizer, self).__init__()
11
+
12
+ # First standardize values and fill missing arguments (if needed) by deriving scale from output shape or vice versa
13
+ scale_factor, output_shape = self.fix_scale_and_size(in_shape, output_shape, scale_factor)
14
+
15
+ # Choose interpolation method, each method has the matching kernel size
16
+ method, kernel_width = {
17
+ "cubic": (cubic, 4.0),
18
+ "lanczos2": (lanczos2, 4.0),
19
+ "lanczos3": (lanczos3, 6.0),
20
+ "box": (box, 1.0),
21
+ "linear": (linear, 2.0),
22
+ None: (cubic, 4.0) # set default interpolation method as cubic
23
+ }.get(kernel)
24
+
25
+ # Antialiasing is only used when downscaling
26
+ antialiasing *= (np.any(np.array(scale_factor) < 1))
27
+
28
+ # Sort indices of dimensions according to scale of each dimension. since we are going dim by dim this is efficient
29
+ sorted_dims = np.argsort(np.array(scale_factor))
30
+ self.sorted_dims = [int(dim) for dim in sorted_dims if scale_factor[dim] != 1]
31
+
32
+ # Iterate over dimensions to calculate local weights for resizing and resize each time in one direction
33
+ field_of_view_list = []
34
+ weights_list = []
35
+ for dim in self.sorted_dims:
36
+ # for each coordinate (along 1 dim), calculate which coordinates in the input image affect its result and the
37
+ # weights that multiply the values there to get its result.
38
+ weights, field_of_view = self.contributions(in_shape[dim], output_shape[dim], scale_factor[dim], method,
39
+ kernel_width, antialiasing)
40
+
41
+ # convert to torch tensor
42
+ weights = torch.tensor(weights.T, dtype=torch.float32)
43
+
44
+ # We add singleton dimensions to the weight matrix so we can multiply it with the big tensor we get for
45
+ # tmp_im[field_of_view.T], (bsxfun style)
46
+ weights_list.append(
47
+ nn.Parameter(torch.reshape(weights, list(weights.shape) + (len(scale_factor) - 1) * [1]),
48
+ requires_grad=False))
49
+ field_of_view_list.append(
50
+ nn.Parameter(torch.tensor(field_of_view.T.astype(np.int32), dtype=torch.long), requires_grad=False))
51
+
52
+ self.field_of_view = nn.ParameterList(field_of_view_list)
53
+ self.weights = nn.ParameterList(weights_list)
54
+
55
+ def forward(self, in_tensor):
56
+ x = in_tensor
57
+
58
+ # Use the affecting position values and the set of weights to calculate the result of resizing along this 1 dim
59
+ for dim, fov, w in zip(self.sorted_dims, self.field_of_view, self.weights):
60
+ # To be able to act on each dim, we swap so that dim 0 is the wanted dim to resize
61
+ x = torch.transpose(x, dim, 0)
62
+
63
+ # This is a bit of a complicated multiplication: x[field_of_view.T] is a tensor of order image_dims+1.
64
+ # for each pixel in the output-image it matches the positions the influence it from the input image (along 1 dim
65
+ # only, this is why it only adds 1 dim to 5the shape). We then multiply, for each pixel, its set of positions with
66
+ # the matching set of weights. we do this by this big tensor element-wise multiplication (MATLAB bsxfun style:
67
+ # matching dims are multiplied element-wise while singletons mean that the matching dim is all multiplied by the
68
+ # same number
69
+ x = torch.sum(x[fov] * w, dim=0)
70
+
71
+ # Finally we swap back the axes to the original order
72
+ x = torch.transpose(x, dim, 0)
73
+
74
+ return x
75
+
76
+ def fix_scale_and_size(self, input_shape, output_shape, scale_factor):
77
+ # First fixing the scale-factor (if given) to be standardized the function expects (a list of scale factors in the
78
+ # same size as the number of input dimensions)
79
+ if scale_factor is not None:
80
+ # By default, if scale-factor is a scalar we assume 2d resizing and duplicate it.
81
+ if np.isscalar(scale_factor) and len(input_shape) > 1:
82
+ scale_factor = [scale_factor, scale_factor]
83
+
84
+ # We extend the size of scale-factor list to the size of the input by assigning 1 to all the unspecified scales
85
+ scale_factor = list(scale_factor)
86
+ scale_factor = [1] * (len(input_shape) - len(scale_factor)) + scale_factor
87
+
88
+ # Fixing output-shape (if given): extending it to the size of the input-shape, by assigning the original input-size
89
+ # to all the unspecified dimensions
90
+ if output_shape is not None:
91
+ output_shape = list(input_shape[len(output_shape):]) + list(np.uint(np.array(output_shape)))
92
+
93
+ # Dealing with the case of non-give scale-factor, calculating according to output-shape. note that this is
94
+ # sub-optimal, because there can be different scales to the same output-shape.
95
+ if scale_factor is None:
96
+ scale_factor = 1.0 * np.array(output_shape) / np.array(input_shape)
97
+
98
+ # Dealing with missing output-shape. calculating according to scale-factor
99
+ if output_shape is None:
100
+ output_shape = np.uint(np.ceil(np.array(input_shape) * np.array(scale_factor)))
101
+
102
+ return scale_factor, output_shape
103
+
104
+ def contributions(self, in_length, out_length, scale, kernel, kernel_width, antialiasing):
105
+ # This function calculates a set of 'filters' and a set of field_of_view that will later on be applied
106
+ # such that each position from the field_of_view will be multiplied with a matching filter from the
107
+ # 'weights' based on the interpolation method and the distance of the sub-pixel location from the pixel centers
108
+ # around it. This is only done for one dimension of the image.
109
+
110
+ # When anti-aliasing is activated (default and only for downscaling) the receptive field is stretched to size of
111
+ # 1/sf. this means filtering is more 'low-pass filter'.
112
+ fixed_kernel = (lambda arg: scale * kernel(scale * arg)) if antialiasing else kernel
113
+ kernel_width *= 1.0 / scale if antialiasing else 1.0
114
+
115
+ # These are the coordinates of the output image
116
+ out_coordinates = np.arange(1, out_length + 1)
117
+
118
+ # since both scale-factor and output size can be provided simulatneously, perserving the center of the image requires shifting
119
+ # the output coordinates. the deviation is because out_length doesn't necesary equal in_length*scale.
120
+ # to keep the center we need to subtract half of this deivation so that we get equal margins for boths sides and center is preserved.
121
+ shifted_out_coordinates = out_coordinates - (out_length - in_length * scale) / 2
122
+
123
+ # These are the matching positions of the output-coordinates on the input image coordinates.
124
+ # Best explained by example: say we have 4 horizontal pixels for HR and we downscale by SF=2 and get 2 pixels:
125
+ # [1,2,3,4] -> [1,2]. Remember each pixel number is the middle of the pixel.
126
+ # The scaling is done between the distances and not pixel numbers (the right boundary of pixel 4 is transformed to
127
+ # the right boundary of pixel 2. pixel 1 in the small image matches the boundary between pixels 1 and 2 in the big
128
+ # one and not to pixel 2. This means the position is not just multiplication of the old pos by scale-factor).
129
+ # So if we measure distance from the left border, middle of pixel 1 is at distance d=0.5, border between 1 and 2 is
130
+ # at d=1, and so on (d = p - 0.5). we calculate (d_new = d_old / sf) which means:
131
+ # (p_new-0.5 = (p_old-0.5) / sf) -> p_new = p_old/sf + 0.5 * (1-1/sf)
132
+ match_coordinates = shifted_out_coordinates / scale + 0.5 * (1 - 1 / scale)
133
+
134
+ # This is the left boundary to start multiplying the filter from, it depends on the size of the filter
135
+ left_boundary = np.floor(match_coordinates - kernel_width / 2)
136
+
137
+ # Kernel width needs to be enlarged because when covering has sub-pixel borders, it must 'see' the pixel centers
138
+ # of the pixels it only covered a part from. So we add one pixel at each side to consider (weights can zeroize them)
139
+ expanded_kernel_width = np.ceil(kernel_width) + 2
140
+
141
+ # Determine a set of field_of_view for each each output position, these are the pixels in the input image
142
+ # that the pixel in the output image 'sees'. We get a matrix whos horizontal dim is the output pixels (big) and the
143
+ # vertical dim is the pixels it 'sees' (kernel_size + 2)
144
+ field_of_view = np.squeeze(
145
+ np.int16(np.expand_dims(left_boundary, axis=1) + np.arange(expanded_kernel_width) - 1))
146
+
147
+ # Assign weight to each pixel in the field of view. A matrix whos horizontal dim is the output pixels and the
148
+ # vertical dim is a list of weights matching to the pixel in the field of view (that are specified in
149
+ # 'field_of_view')
150
+ weights = fixed_kernel(1.0 * np.expand_dims(match_coordinates, axis=1) - field_of_view - 1)
151
+
152
+ # Normalize weights to sum up to 1. be careful from dividing by 0
153
+ sum_weights = np.sum(weights, axis=1)
154
+ sum_weights[sum_weights == 0] = 1.0
155
+ weights = 1.0 * weights / np.expand_dims(sum_weights, axis=1)
156
+
157
+ # We use this mirror structure as a trick for reflection padding at the boundaries
158
+ mirror = np.uint(np.concatenate((np.arange(in_length), np.arange(in_length - 1, -1, step=-1))))
159
+ field_of_view = mirror[np.mod(field_of_view, mirror.shape[0])]
160
+
161
+ # Get rid of weights and pixel positions that are of zero weight
162
+ non_zero_out_pixels = np.nonzero(np.any(weights, axis=0))
163
+ weights = np.squeeze(weights[:, non_zero_out_pixels])
164
+ field_of_view = np.squeeze(field_of_view[:, non_zero_out_pixels])
165
+
166
+ # Final products are the relative positions and the matching weights, both are output_size X fixed_kernel_size
167
+ return weights, field_of_view
168
+
169
+
170
+ # These next functions are all interpolation methods. x is the distance from the left pixel center
171
+
172
+
173
+ def cubic(x):
174
+ absx = np.abs(x)
175
+ absx2 = absx ** 2
176
+ absx3 = absx ** 3
177
+ return ((1.5 * absx3 - 2.5 * absx2 + 1) * (absx <= 1) +
178
+ (-0.5 * absx3 + 2.5 * absx2 - 4 * absx + 2) * ((1 < absx) & (absx <= 2)))
179
+
180
+
181
+ def lanczos2(x):
182
+ return (((np.sin(pi * x) * np.sin(pi * x / 2) + np.finfo(np.float32).eps) /
183
+ ((pi ** 2 * x ** 2 / 2) + np.finfo(np.float32).eps))
184
+ * (abs(x) < 2))
185
+
186
+
187
+ def box(x):
188
+ return ((-0.5 <= x) & (x < 0.5)) * 1.0
189
+
190
+
191
+ def lanczos3(x):
192
+ return (((np.sin(pi * x) * np.sin(pi * x / 3) + np.finfo(np.float32).eps) /
193
+ ((pi ** 2 * x ** 2 / 3) + np.finfo(np.float32).eps))
194
+ * (abs(x) < 3))
195
+
196
+
197
+ def linear(x):
198
+ return (x + 1) * ((-1 <= x) & (x < 0)) + (1 - x) * ((0 <= x) & (x <= 1))