├── evaluations
├── requirements.txt
├── README.md
└── evaluator.py
├── guided_diffusion
├── __init__.py
├── losses.py
├── dist_util.py
├── respace.py
├── nn.py
├── resample.py
├── image_datasets.py
├── fp16_util.py
├── train_util.py
├── script_util.py
├── logger.py
├── unet.py
└── gaussian_diffusion.py
├── .gitignore
├── LICENSE
├── image_sample.py
├── classifier_sample.py
└── README.md
/evaluations/requirements.txt:
--------------------------------------------------------------------------------
1 | tensorflow-gpu>=2.0
2 | scipy
3 | requests
4 | tqdm
--------------------------------------------------------------------------------
/guided_diffusion/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | Codebase for "Improved Denoising Diffusion Probabilistic Models".
3 | """
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | __pycache__/
3 | classify_image_graph_def.pb
4 | models/
5 | *.npz
6 | RESULTS/
7 | guided_diffusion.egg-info/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 OpenAI
4 | Copyright (c) 2021 Yandex Research
5 | Copyright (c) 2022 Susung Hong
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in all
15 | copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 | SOFTWARE.
24 |
--------------------------------------------------------------------------------
/guided_diffusion/losses.py:
--------------------------------------------------------------------------------
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
78 |
--------------------------------------------------------------------------------
/guided_diffusion/dist_util.py:
--------------------------------------------------------------------------------
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 | os.environ["NCCL_DEBUG"] = "INFO"
29 |
30 | comm = MPI.COMM_WORLD
31 | backend = "gloo" if not th.cuda.is_available() else "nccl"
32 |
33 | if backend == "gloo":
34 | hostname = "localhost"
35 | else:
36 | hostname = socket.gethostbyname(socket.getfqdn())
37 | os.environ["MASTER_ADDR"] = comm.bcast(hostname, root=0)
38 | os.environ["RANK"] = str(comm.rank)
39 | os.environ["WORLD_SIZE"] = str(comm.size)
40 |
41 | port = comm.bcast(_find_free_port(), root=0)
42 | os.environ["MASTER_PORT"] = str(port)
43 | dist.init_process_group(backend=backend, init_method="env://")
44 |
45 |
46 | def dev():
47 | """
48 | Get the device to use for torch.distributed.
49 | """
50 | if th.cuda.is_available():
51 | return th.device(f"cuda")
52 | return th.device("cpu")
53 |
54 |
55 | def load_state_dict(path, **kwargs):
56 | """
57 | Load a PyTorch file without redundant fetches across MPI ranks.
58 | """
59 | chunk_size = 2 ** 30 # MPI has a relatively small size limit
60 | if MPI.COMM_WORLD.Get_rank() == 0:
61 | with bf.BlobFile(path, "rb") as f:
62 | data = f.read()
63 | num_chunks = len(data) // chunk_size
64 | if len(data) % chunk_size:
65 | num_chunks += 1
66 | MPI.COMM_WORLD.bcast(num_chunks)
67 | for i in range(0, len(data), chunk_size):
68 | MPI.COMM_WORLD.bcast(data[i : i + chunk_size])
69 | else:
70 | num_chunks = MPI.COMM_WORLD.bcast(None)
71 | data = bytes()
72 | for _ in range(num_chunks):
73 | data += MPI.COMM_WORLD.bcast(None)
74 |
75 | return th.load(io.BytesIO(data), **kwargs)
76 |
77 |
78 | def sync_params(params):
79 | """
80 | Synchronize a sequence of Tensors across ranks from rank 0.
81 | """
82 | for p in params:
83 | with th.no_grad():
84 | dist.broadcast(p, 0)
85 |
86 |
87 | def _find_free_port():
88 | try:
89 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
90 | s.bind(("", 0))
91 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
92 | return s.getsockname()[1]
93 | finally:
94 | s.close()
95 |
--------------------------------------------------------------------------------
/image_sample.py:
--------------------------------------------------------------------------------
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 | import yaml
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 | create_model_and_diffusion,
19 | add_dict_to_argparser,
20 | args_to_dict,
21 | sag_defaults,
22 | )
23 | import datetime
24 |
25 | def get_datetime():
26 | UTC = datetime.timezone(datetime.timedelta(hours=0))
27 | date = datetime.datetime.now(UTC).strftime("%Y_%m_%d-%I%M%S_%p")
28 | return date
29 |
30 | def main():
31 | args = create_argparser().parse_args()
32 | save_name = f"{get_datetime()}"
33 | dist_util.setup_dist()
34 | logger.configure(dir=f'RESULTS/{save_name}')
35 |
36 | with open(os.path.join(logger.get_dir(), 'config.yaml'), 'w') as f:
37 | yaml.dump(args.__dict__, f)
38 |
39 | logger.log("creating model and diffusion...")
40 | model, diffusion = create_model_and_diffusion(
41 | sel_attn_depth=args.sel_attn_depth,
42 | sel_attn_block=args.sel_attn_block,
43 | **args_to_dict(args, model_and_diffusion_defaults().keys())
44 | )
45 | model.load_state_dict(
46 | dist_util.load_state_dict(args.model_path, map_location="cpu")
47 | )
48 | model.to(dist_util.dev())
49 | if args.use_fp16:
50 | model.convert_to_fp16()
51 | model.eval()
52 |
53 | logger.log("sampling...")
54 | all_images = []
55 | all_labels = []
56 | guidance_kwargs = {}
57 | guidance_kwargs["guide_start"] = args.guide_start
58 | guidance_kwargs["guide_scale"] = args.guide_scale
59 | guidance_kwargs["blur_sigma"] = args.blur_sigma
60 |
61 | while len(all_images) * args.batch_size < args.num_samples:
62 | model_kwargs = {}
63 | if args.class_cond:
64 | classes = th.randint(
65 | low=0, high=NUM_CLASSES, size=(args.batch_size,), device=dist_util.dev()
66 | )
67 | model_kwargs["y"] = classes
68 | sample_fn = (
69 | diffusion.p_sample_loop if not args.use_ddim else diffusion.ddim_sample_loop
70 | )
71 | sample = sample_fn(
72 | model,
73 | (args.batch_size, 3, args.image_size, args.image_size),
74 | clip_denoised=args.clip_denoised,
75 | model_kwargs=model_kwargs,
76 | guidance_kwargs=guidance_kwargs
77 | )
78 | sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)
79 | sample = sample.permute(0, 2, 3, 1)
80 | sample = sample.contiguous()
81 |
82 | gathered_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())]
83 | dist.all_gather(gathered_samples, sample) # gather not supported with NCCL
84 | all_images.extend([sample.cpu().numpy() for sample in gathered_samples])
85 | if args.class_cond:
86 | gathered_labels = [
87 | th.zeros_like(classes) for _ in range(dist.get_world_size())
88 | ]
89 | dist.all_gather(gathered_labels, classes)
90 | all_labels.extend([labels.cpu().numpy() for labels in gathered_labels])
91 | logger.log(f"created {len(all_images) * args.batch_size} samples")
92 |
93 | arr = np.concatenate(all_images, axis=0)
94 | arr = arr[: args.num_samples]
95 | if args.class_cond:
96 | label_arr = np.concatenate(all_labels, axis=0)
97 | label_arr = label_arr[: args.num_samples]
98 | if dist.get_rank() == 0:
99 | shape_str = "x".join([str(x) for x in arr.shape])
100 | out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz")
101 | logger.log(f"saving to {out_path}")
102 | if args.class_cond:
103 | np.savez(out_path, arr, label_arr)
104 | else:
105 | np.savez(out_path, arr)
106 |
107 | dist.barrier()
108 | logger.log("sampling complete")
109 |
110 |
111 | def create_argparser():
112 | defaults = dict(
113 | clip_denoised=True,
114 | num_samples=10000,
115 | batch_size=16,
116 | use_ddim=False,
117 | model_path="",
118 | )
119 | defaults.update(model_and_diffusion_defaults())
120 | defaults.update(sag_defaults())
121 | parser = argparse.ArgumentParser()
122 | add_dict_to_argparser(parser, defaults)
123 | return parser
124 |
125 |
126 | if __name__ == "__main__":
127 | main()
128 |
--------------------------------------------------------------------------------
/guided_diffusion/respace.py:
--------------------------------------------------------------------------------
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)
129 |
--------------------------------------------------------------------------------
/guided_diffusion/nn.py:
--------------------------------------------------------------------------------
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
171 |
--------------------------------------------------------------------------------
/classifier_sample.py:
--------------------------------------------------------------------------------
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 | import yaml
14 |
15 | from guided_diffusion import dist_util, logger
16 | from guided_diffusion.script_util import (NUM_CLASSES, add_dict_to_argparser,
17 | args_to_dict, classifier_defaults,
18 | create_classifier,
19 | create_model_and_diffusion,
20 | model_and_diffusion_defaults,
21 | sag_defaults,)
22 |
23 | import datetime
24 |
25 | def get_datetime():
26 | UTC = datetime.timezone(datetime.timedelta(hours=0))
27 | date = datetime.datetime.now(UTC).strftime("%Y_%m_%d-%I%M%S_%p")
28 | return date
29 |
30 | def main():
31 | args = create_argparser().parse_args()
32 | save_name = f"{get_datetime()}"
33 | dist_util.setup_dist()
34 | logger.configure(dir=f'RESULTS/{save_name}')
35 |
36 | with open(os.path.join(logger.get_dir(), 'config.yaml'), 'w') as f:
37 | yaml.dump(args.__dict__, f)
38 |
39 | logger.log("creating model and diffusion...")
40 | model, diffusion = create_model_and_diffusion(
41 | sel_attn_depth=args.sel_attn_depth,
42 | sel_attn_block=args.sel_attn_block,
43 | **args_to_dict(args, model_and_diffusion_defaults().keys())
44 | )
45 |
46 | model.load_state_dict(
47 | dist_util.load_state_dict(args.model_path, map_location="cpu")
48 | )
49 | model.to(dist_util.dev())
50 | if args.use_fp16:
51 | model.convert_to_fp16()
52 | model.eval()
53 |
54 | logger.log("loading classifier...")
55 | classifier = create_classifier(**args_to_dict(args, classifier_defaults().keys()))
56 | classifier.load_state_dict(
57 | dist_util.load_state_dict(args.classifier_path, map_location="cpu")
58 | )
59 | classifier.to(dist_util.dev())
60 | if args.classifier_use_fp16:
61 | classifier.convert_to_fp16()
62 | classifier.eval()
63 |
64 | def cond_fn(x, t, y=None):
65 | assert y is not None
66 | with th.enable_grad():
67 | x_in = x.detach().requires_grad_(True)
68 | logits = classifier(x_in, t)
69 | log_probs = F.log_softmax(logits, dim=-1)
70 | selected = log_probs[range(len(logits)), y.view(-1)]
71 | return th.autograd.grad(selected.sum(), x_in)[0] * args.classifier_scale
72 |
73 | def model_fn(x, t, y=None):
74 | assert y is not None
75 | return model(x, t, y if args.class_cond else None)
76 |
77 | logger.log("sampling...")
78 | all_images = []
79 | all_labels = []
80 | shape_str = None
81 | guidance_kwargs = {}
82 | guidance_kwargs["guide_start"] = args.guide_start
83 | guidance_kwargs["guide_scale"] = args.guide_scale
84 | guidance_kwargs["blur_sigma"] = args.blur_sigma
85 |
86 | while len(all_images) * args.batch_size < args.num_samples:
87 | model_kwargs = {}
88 | classes = th.randint(
89 | low=0, high=NUM_CLASSES, size=(args.batch_size,), device=dist_util.dev()
90 | )
91 | model_kwargs["y"] = classes
92 | sample_fn = (
93 | diffusion.p_sample_loop if not args.use_ddim else diffusion.ddim_sample_loop
94 | )
95 | sample = sample_fn(
96 | model_fn,
97 | (args.batch_size, 3, args.image_size, args.image_size),
98 | clip_denoised=args.clip_denoised,
99 | model_kwargs=model_kwargs,
100 | cond_fn=None if not args.classifier_guidance else cond_fn,
101 | device=dist_util.dev(),
102 | guidance_kwargs=guidance_kwargs
103 | )
104 | sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)
105 | sample = sample.permute(0, 2, 3, 1)
106 | sample = sample.contiguous()
107 |
108 | gathered_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())]
109 | dist.all_gather(gathered_samples, sample) # gather not supported with NCCL
110 | all_images.extend([sample.cpu().numpy() for sample in gathered_samples])
111 | gathered_labels = [th.zeros_like(classes) for _ in range(dist.get_world_size())]
112 | dist.all_gather(gathered_labels, classes)
113 | all_labels.extend([labels.cpu().numpy() for labels in gathered_labels])
114 | logger.log(f"created {len(all_images) * args.batch_size} samples")
115 |
116 | arr = np.concatenate(all_images, axis=0)
117 | arr = arr[: args.num_samples]
118 | label_arr = np.concatenate(all_labels, axis=0)
119 | label_arr = label_arr[: args.num_samples]
120 | if dist.get_rank() == 0:
121 | shape_str = "x".join([str(x) for x in arr.shape])
122 | out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz")
123 | logger.log(f"saving to {out_path}")
124 | np.savez(out_path, arr, label_arr)
125 |
126 | dist.barrier()
127 | logger.log("sampling complete")
128 |
129 |
130 | def create_argparser():
131 | defaults = dict(
132 | clip_denoised=True,
133 | num_samples=10000,
134 | batch_size=16,
135 | use_ddim=False,
136 | model_path="",
137 | classifier_path="",
138 | classifier_scale=1.0,
139 | )
140 | defaults.update(model_and_diffusion_defaults())
141 | defaults.update(classifier_defaults())
142 | defaults.update(sag_defaults())
143 | parser = argparse.ArgumentParser()
144 | add_dict_to_argparser(parser, defaults)
145 | return parser
146 |
147 |
148 | if __name__ == "__main__":
149 | main()
150 |
--------------------------------------------------------------------------------
/guided_diffusion/resample.py:
--------------------------------------------------------------------------------
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()
155 |
--------------------------------------------------------------------------------
/guided_diffusion/image_datasets.py:
--------------------------------------------------------------------------------
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]
168 |
--------------------------------------------------------------------------------
/evaluations/README.md:
--------------------------------------------------------------------------------
1 | # Evaluations
2 |
3 | To compare different generative models, we use FID, sFID, Precision, Recall, and Inception Score. These metrics can all be calculated using batches of samples, which we store in `.npz` (numpy) files.
4 |
5 | # Download batches
6 |
7 | We provide pre-computed sample batches for the reference datasets, our diffusion models, and several baselines we compare against. These are all stored in `.npz` format.
8 |
9 | Reference dataset batches contain pre-computed statistics over the whole dataset, as well as 10,000 images for computing Precision and Recall. All other batches contain 50,000 images which can be used to compute statistics and Precision/Recall.
10 |
11 | Here are links to download all of the sample and reference batches:
12 |
13 | * LSUN
14 | * LSUN bedroom: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/bedroom/VIRTUAL_lsun_bedroom256.npz)
15 | * [ADM (dropout)](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/bedroom/admnet_dropout_lsun_bedroom.npz)
16 | * [DDPM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/bedroom/ddpm_lsun_bedroom.npz)
17 | * [IDDPM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/bedroom/iddpm_lsun_bedroom.npz)
18 | * [StyleGAN](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/bedroom/stylegan_lsun_bedroom.npz)
19 | * LSUN cat: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/cat/VIRTUAL_lsun_cat256.npz)
20 | * [ADM (dropout)](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/cat/admnet_dropout_lsun_cat.npz)
21 | * [StyleGAN2](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/cat/stylegan2_lsun_cat.npz)
22 | * LSUN horse: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/horse/VIRTUAL_lsun_horse256.npz)
23 | * [ADM (dropout)](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/horse/admnet_dropout_lsun_horse.npz)
24 | * [ADM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/lsun/horse/admnet_lsun_horse.npz)
25 |
26 | * ImageNet
27 | * ImageNet 64x64: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/64/VIRTUAL_imagenet64_labeled.npz)
28 | * [ADM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/64/admnet_imagenet64.npz)
29 | * [IDDPM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/64/iddpm_imagenet64.npz)
30 | * [BigGAN](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/64/biggan_deep_imagenet64.npz)
31 | * ImageNet 128x128: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/128/VIRTUAL_imagenet128_labeled.npz)
32 | * [ADM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/128/admnet_imagenet128.npz)
33 | * [ADM-G](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/128/admnet_guided_imagenet128.npz)
34 | * [ADM-G, 25 steps](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/128/admnet_guided_25step_imagenet128.npz)
35 | * [BigGAN-deep (trunc=1.0)](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/128/biggan_deep_trunc1_imagenet128.npz)
36 | * ImageNet 256x256: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/VIRTUAL_imagenet256_labeled.npz)
37 | * [ADM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/admnet_imagenet256.npz)
38 | * [ADM-G](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/admnet_guided_imagenet256.npz)
39 | * [ADM-G, 25 step](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/admnet_guided_25step_imagenet256.npz)
40 | * [ADM-G + ADM-U](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/admnet_guided_upsampled_imagenet256.npz)
41 | * [ADM-U](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/admnet_upsampled_imagenet256.npz)
42 | * [BigGAN-deep (trunc=1.0)](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/biggan_deep_trunc1_imagenet256.npz)
43 | * ImageNet 512x512: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/VIRTUAL_imagenet512.npz)
44 | * [ADM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/admnet_imagenet512.npz)
45 | * [ADM-G](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/admnet_guided_imagenet512.npz)
46 | * [ADM-G, 25 step](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/admnet_guided_25step_imagenet512.npz)
47 | * [ADM-G + ADM-U](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/admnet_guided_upsampled_imagenet512.npz)
48 | * [ADM-U](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/admnet_upsampled_imagenet512.npz)
49 | * [BigGAN-deep (trunc=1.0)](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/biggan_deep_trunc1_imagenet512.npz)
50 |
51 | # Run evaluations
52 |
53 | First, generate or download a batch of samples and download the corresponding reference batch for the given dataset. For this example, we'll use ImageNet 256x256, so the refernce batch is `VIRTUAL_imagenet256_labeled.npz` and we can use the sample batch `admnet_guided_upsampled_imagenet256.npz`.
54 |
55 | Next, run the `evaluator.py` script. The requirements of this script can be found in [requirements.txt](requirements.txt). Pass two arguments to the script: the reference batch and the sample batch. The script will download the InceptionV3 model used for evaluations into the current working directory (if it is not already present). This file is roughly 100MB.
56 |
57 | The output of the script will look something like this, where the first `...` is a bunch of verbose TensorFlow logging:
58 |
59 | ```
60 | $ python evaluator.py VIRTUAL_imagenet256_labeled.npz admnet_guided_upsampled_imagenet256.npz
61 | ...
62 | computing reference batch activations...
63 | computing/reading reference batch statistics...
64 | computing sample batch activations...
65 | computing/reading sample batch statistics...
66 | Computing evaluations...
67 | Inception Score: 215.8370361328125
68 | FID: 3.9425574129223264
69 | sFID: 6.140433703346162
70 | Precision: 0.8265
71 | Recall: 0.5309
72 | ```
73 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Self-Attention Diffusion Guidance (ICCV`23)
2 |
3 |
4 |
5 |
6 | 
7 | This is the implementation of the paper Improving Sample Quality of Diffusion Models Using Self-Attention Guidance by Hong et al. To gain insight from our exploration of the self-attention maps of diffusion models and for detailed explanations, please see our [Paper](https://arxiv.org/abs/2210.00939) and [Project Page](https://ku-cvlab.github.io/Self-Attention-Guidance).
8 |
9 | This repository is based on [openai/guided-diffusion](https://github.com/openai/guided-diffusion), and we modified feature extraction code from [yandex-research/ddpm-segmentation](https://github.com/yandex-research/ddpm-segmentation) to get the self-attention maps. The major implementation of our method is in `./guided_diffusion/gaussian_diffusion.py` and `./guided_diffusion/unet.py`.
10 |
11 | All you need is to setup the environment, download existing models, and sample from them using our implementation. Neither further training nor a dataset is needed to apply self-attention guidance!
12 |
13 | ## Updates
14 |
15 | **2023-08-14:** This repository supports DDIM sampling with SAG.
16 |
17 | **2023-02-19:** The [Gradio Demo](https://huggingface.co/spaces/susunghong/Self-Attention-Guidance):hugs: of SAG for Stable Diffusion is now available
18 |
19 | **2023-02-16:** The Stable Diffusion pipeline of SAG is now available at [huggingface/diffusers](https://huggingface.co/docs/diffusers/api/pipelines/self_attention_guidance) :hugs::firecracker:
20 |
21 | **2023-02-01:** The demo for Stable Diffusion is now available in [Colab](https://colab.research.google.com/github/SusungHong/Self-Attention-Guidance/blob/main/SAG_Stable.ipynb).
22 |
23 | ## Environment
24 | * Python 3.8, PyTorch 1.11.0
25 | * 8 x NVIDIA RTX 3090 (set `backend="gloo"` in `./guided_diffusion/dist_util.py` if P2P access is not available)
26 | ```
27 | git clone https://github.com/KU-CVLAB/Self-Attention-Guidance
28 | conda create -n sag python=3.8 anaconda
29 | conda activate sag
30 | conda install mpi4py
31 | pip install torch==1.11.0+cu113 torchvision==0.12.0+cu113 -f https://download.pytorch.org/whl/torch_stable.html
32 | pip install blobfile
33 | ```
34 |
35 | ## Downloading Pretrained Diffusion Models (and Classifiers for CG)
36 | Pretrained weights for ImageNet and LSUN can be downloaded from [the repository](https://github.com/openai/guided-diffusion). Download and place them in the `./models/` directory.
37 |
38 | ## Sampling from Pretrained Diffusion Models
39 | You can sample from pretrained diffusion models with self-attention guidance by changing `SAG_FLAGS` in the following commands. Note that sampling with `--guide_scale 1.0` means sampling without self-attention guidance. Below are the 4 examples.
40 |
41 | * ImageNet 128x128 model (`--classifier_guidance False` deactivates classifier guidance):
42 | ```
43 | SAMPLE_FLAGS="--batch_size 64 --num_samples 10000 --timestep_respacing 250"
44 | 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"
45 | SAG_FLAGS="--guide_scale 1.1 --guide_start 250 --sel_attn_block output --sel_attn_depth 8 --blur_sigma 3 --classifier_guidance True"
46 | mpiexec -n $NUM_GPUS python classifier_sample.py $SAG_FLAGS $MODEL_FLAGS --classifier_scale 0.5 --classifier_path models/128x128_classifier.pt --model_path models/128x128_diffusion.pt $SAMPLE_FLAGS
47 | ```
48 |
49 | * ImageNet 256x256 model (`--class_cond True` for conditional models):
50 | ```
51 | SAMPLE_FLAGS="--batch_size 16 --num_samples 10000 --timestep_respacing 250"
52 | 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"
53 | SAG_FLAGS="--guide_scale 1.5 --guide_start 250 --sel_attn_block output --sel_attn_depth 2 --blur_sigma 9 --classifier_guidance False"
54 | mpiexec -n $NUM_GPUS python classifier_sample.py $SAG_FLAGS $MODEL_FLAGS --classifier_scale 0.0 --classifier_path models/256x256_classifier.pt --model_path models/256x256_diffusion_uncond.pt $SAMPLE_FLAGS
55 | ```
56 |
57 | * LSUN Cat model (respaced to 250 steps):
58 | ```
59 | SAMPLE_FLAGS="--batch_size 16 --num_samples 10000 --timestep_respacing 250"
60 | 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"
61 | SAG_FLAGS="--guide_scale 1.05 --guide_start 250 --sel_attn_block output --sel_attn_depth 2 --blur_sigma 9 --classifier_guidance False"
62 | mpiexec -n $NUM_GPUS python image_sample.py $SAG_FLAGS $MODEL_FLAGS --model_path models/lsun_cat.pt $SAMPLE_FLAGS
63 | ```
64 |
65 | * LSUN Horse model (respaced to 250 steps):
66 | ```
67 | SAMPLE_FLAGS="--batch_size 16 --num_samples 10000 --timestep_respacing 250"
68 | 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"
69 | SAG_FLAGS="--guide_scale 1.01 --guide_start 250 --sel_attn_block output --sel_attn_depth 2 --blur_sigma 9 --classifier_guidance False"
70 | mpiexec -n $NUM_GPUS python image_sample.py $SAG_FLAGS $MODEL_FLAGS --model_path models/lsun_horse.pt $SAMPLE_FLAGS
71 | ```
72 |
73 | * ImageNet 128x128 model (DDIM 25 steps):
74 | ```
75 | 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"
76 | 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"
77 | SAMPLE_FLAGS="--batch_size 8 --num_samples 8 --timestep_respacing ddim25 --use_ddim True"
78 | SAG_FLAGS="--guide_scale 1.1 --guide_start 25 --sel_attn_block output --sel_attn_depth 8 --blur_sigma 3 --classifier_guidance True"
79 | mpiexec -n $NUM_GPUS python classifier_sample.py \
80 | --model_path models/128x128_diffusion.pt \
81 | --classifier_path models/128x128_classifier.pt \
82 | $MODEL_FLAGS $CLASSIFIER_FLAGS $SAMPLE_FLAGS $SAG_FLAGS
83 | ```
84 |
85 | # Results
86 |
87 | **Compatibility of self-attention guidance (SAG) and classifier guidance (CG) on ImageNet 128x128 model:**
88 |
89 | | SAG | CG | FID | sFID | Precision | Recall |
90 | |---|---|---|---|---|---|
91 | | | | 5.91 | 5.09 | 0.70 | 0.65 |
92 | | | V | 2.97 | 5.09 | 0.78 | 0.59 |
93 | | V | | 5.11 | 4.09 | 0.72 | 0.65 |
94 | | V | V | 2.58 | 4.35 | 0.79 | 0.59 |
95 |
96 | **Results on pretrained models:**
97 |
98 | | Model | # of steps | Self-attention guidance scale | FID | sFID | IS | Precision | Recall |
99 | |:---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
100 | | ImageNet 256×256 (Uncond.) | 250 | 0.0 (baseline)
0.5
0.8 | 26.21
20.31
20.08 | 6.35
5.09
5.77 | 39.70
45.30
45.56 | 0.61
0.66
0.68 | 0.63
0.61
0.59 |
101 | | ImageNet 256×256 (Cond.) | 250 | 0.0 (baseline)
0.2 | 10.94
9.41 | 6.02
5.28 | 100.98
104.79 | 0.69
0.70 | 0.63
0.62 |
102 | | LSUN Cat 256×256 | 250 | 0.0 (baseline)
0.05 | 7.03
6.87 | 8.24
8.21 | -
- | 0.60
0.60 | 0.53
0.50 |
103 | | LSUN Horse 256×256 | 250 | 0.0 (baseline)
0.01 | 3.45
3.43 | 7.55
7.51 | -
- | 0.68
0.68 | 0.56
0.55 |
104 |
105 | # Cite as
106 | ```
107 | @inproceedings{hong2023improving,
108 | title={Improving sample quality of diffusion models using self-attention guidance},
109 | author={Hong, Susung and Lee, Gyuseong and Jang, Wooseok and Kim, Seungryong},
110 | booktitle={Proceedings of the IEEE/CVF International Conference on Computer Vision},
111 | pages={7462--7471},
112 | year={2023}
113 | }
114 | ```
115 |
--------------------------------------------------------------------------------
/guided_diffusion/fp16_util.py:
--------------------------------------------------------------------------------
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)
237 |
--------------------------------------------------------------------------------
/guided_diffusion/train_util.py:
--------------------------------------------------------------------------------
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)
302 |
--------------------------------------------------------------------------------
/guided_diffusion/script_util.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import inspect
3 | from typing import Tuple
4 |
5 | from . import gaussian_diffusion as gd
6 | from .respace import SpacedDiffusion, space_timesteps
7 | from .unet import EncoderUNetModel, SuperResModel, UNetModel
8 |
9 | NUM_CLASSES = 1000
10 |
11 | def sag_defaults():
12 | """
13 | Defaults for self-attention guidance
14 | """
15 | return dict(
16 | guide_scale=1.5,
17 | guide_start=250,
18 | sel_attn_block="output",
19 | sel_attn_depth=2,
20 | blur_sigma=9,
21 | classifier_guidance=False,
22 | )
23 |
24 |
25 | def diffusion_defaults():
26 | """
27 | Defaults for image and classifier training.
28 | """
29 | return dict(
30 | learn_sigma=False,
31 | diffusion_steps=1000,
32 | noise_schedule="linear",
33 | timestep_respacing="",
34 | use_kl=False,
35 | predict_xstart=False,
36 | rescale_timesteps=False,
37 | rescale_learned_sigmas=False,
38 | )
39 |
40 |
41 | def classifier_defaults():
42 | """
43 | Defaults for classifier models.
44 | """
45 | return dict(
46 | image_size=64,
47 | classifier_use_fp16=False,
48 | classifier_width=128,
49 | classifier_depth=2,
50 | classifier_attention_resolutions="32,16,8", # 16
51 | classifier_use_scale_shift_norm=True, # False
52 | classifier_resblock_updown=True, # False
53 | classifier_pool="attention",
54 | )
55 |
56 |
57 | def model_and_diffusion_defaults():
58 | """
59 | Defaults for image training.
60 | """
61 | res = dict(
62 | image_size=64,
63 | num_channels=128,
64 | num_res_blocks=2,
65 | num_heads=4,
66 | num_heads_upsample=-1,
67 | num_head_channels=-1,
68 | attention_resolutions="16,8",
69 | channel_mult="",
70 | dropout=0.0,
71 | class_cond=False,
72 | use_checkpoint=False,
73 | use_scale_shift_norm=True,
74 | resblock_updown=False,
75 | use_fp16=False,
76 | use_new_attention_order=False,
77 | )
78 | res.update(diffusion_defaults())
79 | return res
80 |
81 |
82 | def classifier_and_diffusion_defaults():
83 | res = classifier_defaults()
84 | res.update(diffusion_defaults())
85 | return res
86 |
87 |
88 | def create_model_and_diffusion(
89 | image_size,
90 | class_cond,
91 | learn_sigma,
92 | num_channels,
93 | num_res_blocks,
94 | channel_mult,
95 | num_heads,
96 | num_head_channels,
97 | num_heads_upsample,
98 | attention_resolutions,
99 | dropout,
100 | diffusion_steps,
101 | noise_schedule,
102 | timestep_respacing,
103 | use_kl,
104 | predict_xstart,
105 | rescale_timesteps,
106 | rescale_learned_sigmas,
107 | use_checkpoint,
108 | use_scale_shift_norm,
109 | resblock_updown,
110 | use_fp16,
111 | use_new_attention_order,
112 | sel_attn_depth,
113 | sel_attn_block,
114 | ) -> Tuple[UNetModel, SpacedDiffusion]:
115 | model = create_model(
116 | image_size,
117 | num_channels,
118 | num_res_blocks,
119 | channel_mult=channel_mult,
120 | learn_sigma=learn_sigma,
121 | class_cond=class_cond,
122 | use_checkpoint=use_checkpoint,
123 | attention_resolutions=attention_resolutions,
124 | num_heads=num_heads,
125 | num_head_channels=num_head_channels,
126 | num_heads_upsample=num_heads_upsample,
127 | use_scale_shift_norm=use_scale_shift_norm,
128 | dropout=dropout,
129 | resblock_updown=resblock_updown,
130 | use_fp16=use_fp16,
131 | use_new_attention_order=use_new_attention_order,
132 | sel_attn_block=sel_attn_block,
133 | sel_attn_depth=sel_attn_depth,
134 | )
135 | diffusion = create_gaussian_diffusion(
136 | steps=diffusion_steps,
137 | learn_sigma=learn_sigma,
138 | noise_schedule=noise_schedule,
139 | use_kl=use_kl,
140 | predict_xstart=predict_xstart,
141 | rescale_timesteps=rescale_timesteps,
142 | rescale_learned_sigmas=rescale_learned_sigmas,
143 | timestep_respacing=timestep_respacing,
144 | sel_attn_block=sel_attn_block,
145 | sel_attn_depth=sel_attn_depth,
146 | num_heads=num_heads,
147 | )
148 | return model, diffusion
149 |
150 |
151 | def create_model(
152 | image_size,
153 | num_channels,
154 | num_res_blocks,
155 | channel_mult="",
156 | learn_sigma=False,
157 | class_cond=False,
158 | use_checkpoint=False,
159 | attention_resolutions="16",
160 | num_heads=1,
161 | num_head_channels=-1,
162 | num_heads_upsample=-1,
163 | use_scale_shift_norm=False,
164 | dropout=0,
165 | resblock_updown=False,
166 | use_fp16=False,
167 | use_new_attention_order=False,
168 | sel_attn_block=None,
169 | sel_attn_depth=None
170 | ):
171 | if channel_mult == "":
172 | if image_size == 512:
173 | channel_mult = (0.5, 1, 1, 2, 2, 4, 4)
174 | elif image_size == 256:
175 | channel_mult = (1, 1, 2, 2, 4, 4)
176 | elif image_size == 128:
177 | channel_mult = (1, 1, 2, 3, 4)
178 | elif image_size == 64:
179 | channel_mult = (1, 2, 3, 4)
180 | else:
181 | raise ValueError(f"unsupported image size: {image_size}")
182 | else:
183 | channel_mult = tuple(int(ch_mult) for ch_mult in channel_mult.split(","))
184 |
185 | attention_ds = []
186 | for res in attention_resolutions.split(","):
187 | attention_ds.append(image_size // int(res))
188 |
189 | return UNetModel(
190 | image_size=image_size,
191 | in_channels=3,
192 | model_channels=num_channels,
193 | out_channels=(3 if not learn_sigma else 6),
194 | num_res_blocks=num_res_blocks,
195 | attention_resolutions=tuple(attention_ds),
196 | dropout=dropout,
197 | channel_mult=channel_mult,
198 | num_classes=(NUM_CLASSES if class_cond else None),
199 | use_checkpoint=use_checkpoint,
200 | use_fp16=use_fp16,
201 | num_heads=num_heads,
202 | num_head_channels=num_head_channels,
203 | num_heads_upsample=num_heads_upsample,
204 | use_scale_shift_norm=use_scale_shift_norm,
205 | resblock_updown=resblock_updown,
206 | use_new_attention_order=use_new_attention_order,
207 | sel_attn_block=sel_attn_block,
208 | sel_attn_depth=sel_attn_depth,
209 | )
210 |
211 |
212 | def create_classifier_and_diffusion(
213 | image_size,
214 | classifier_use_fp16,
215 | classifier_width,
216 | classifier_depth,
217 | classifier_attention_resolutions,
218 | classifier_use_scale_shift_norm,
219 | classifier_resblock_updown,
220 | classifier_pool,
221 | learn_sigma,
222 | diffusion_steps,
223 | noise_schedule,
224 | timestep_respacing,
225 | use_kl,
226 | predict_xstart,
227 | rescale_timesteps,
228 | rescale_learned_sigmas,
229 | ):
230 | classifier = create_classifier(
231 | image_size,
232 | classifier_use_fp16,
233 | classifier_width,
234 | classifier_depth,
235 | classifier_attention_resolutions,
236 | classifier_use_scale_shift_norm,
237 | classifier_resblock_updown,
238 | classifier_pool,
239 | )
240 | diffusion = create_gaussian_diffusion(
241 | steps=diffusion_steps,
242 | learn_sigma=learn_sigma,
243 | noise_schedule=noise_schedule,
244 | use_kl=use_kl,
245 | predict_xstart=predict_xstart,
246 | rescale_timesteps=rescale_timesteps,
247 | rescale_learned_sigmas=rescale_learned_sigmas,
248 | timestep_respacing=timestep_respacing,
249 | )
250 | return classifier, diffusion
251 |
252 |
253 | def create_classifier(
254 | image_size,
255 | classifier_use_fp16,
256 | classifier_width,
257 | classifier_depth,
258 | classifier_attention_resolutions,
259 | classifier_use_scale_shift_norm,
260 | classifier_resblock_updown,
261 | classifier_pool,
262 | ):
263 | if image_size == 512:
264 | channel_mult = (0.5, 1, 1, 2, 2, 4, 4)
265 | elif image_size == 256:
266 | channel_mult = (1, 1, 2, 2, 4, 4)
267 | elif image_size == 128:
268 | channel_mult = (1, 1, 2, 3, 4)
269 | elif image_size == 64:
270 | channel_mult = (1, 2, 3, 4)
271 | else:
272 | raise ValueError(f"unsupported image size: {image_size}")
273 |
274 | attention_ds = []
275 | for res in classifier_attention_resolutions.split(","):
276 | attention_ds.append(image_size // int(res))
277 |
278 | return EncoderUNetModel(
279 | image_size=image_size,
280 | in_channels=3,
281 | model_channels=classifier_width,
282 | out_channels=1000,
283 | num_res_blocks=classifier_depth,
284 | attention_resolutions=tuple(attention_ds),
285 | channel_mult=channel_mult,
286 | use_fp16=classifier_use_fp16,
287 | num_head_channels=64,
288 | use_scale_shift_norm=classifier_use_scale_shift_norm,
289 | resblock_updown=classifier_resblock_updown,
290 | pool=classifier_pool,
291 | )
292 |
293 |
294 | def sr_model_and_diffusion_defaults():
295 | res = model_and_diffusion_defaults()
296 | res["large_size"] = 256
297 | res["small_size"] = 64
298 | arg_names = inspect.getfullargspec(sr_create_model_and_diffusion)[0]
299 | for k in res.copy().keys():
300 | if k not in arg_names:
301 | del res[k]
302 | return res
303 |
304 |
305 | def sr_create_model_and_diffusion(
306 | large_size,
307 | small_size,
308 | class_cond,
309 | learn_sigma,
310 | num_channels,
311 | num_res_blocks,
312 | num_heads,
313 | num_head_channels,
314 | num_heads_upsample,
315 | attention_resolutions,
316 | dropout,
317 | diffusion_steps,
318 | noise_schedule,
319 | timestep_respacing,
320 | use_kl,
321 | predict_xstart,
322 | rescale_timesteps,
323 | rescale_learned_sigmas,
324 | use_checkpoint,
325 | use_scale_shift_norm,
326 | resblock_updown,
327 | use_fp16,
328 | ):
329 | model = sr_create_model(
330 | large_size,
331 | small_size,
332 | num_channels,
333 | num_res_blocks,
334 | learn_sigma=learn_sigma,
335 | class_cond=class_cond,
336 | use_checkpoint=use_checkpoint,
337 | attention_resolutions=attention_resolutions,
338 | num_heads=num_heads,
339 | num_head_channels=num_head_channels,
340 | num_heads_upsample=num_heads_upsample,
341 | use_scale_shift_norm=use_scale_shift_norm,
342 | dropout=dropout,
343 | resblock_updown=resblock_updown,
344 | use_fp16=use_fp16,
345 | )
346 | diffusion = create_gaussian_diffusion(
347 | steps=diffusion_steps,
348 | learn_sigma=learn_sigma,
349 | noise_schedule=noise_schedule,
350 | use_kl=use_kl,
351 | predict_xstart=predict_xstart,
352 | rescale_timesteps=rescale_timesteps,
353 | rescale_learned_sigmas=rescale_learned_sigmas,
354 | timestep_respacing=timestep_respacing,
355 | )
356 | return model, diffusion
357 |
358 |
359 | def sr_create_model(
360 | large_size,
361 | small_size,
362 | num_channels,
363 | num_res_blocks,
364 | learn_sigma,
365 | class_cond,
366 | use_checkpoint,
367 | attention_resolutions,
368 | num_heads,
369 | num_head_channels,
370 | num_heads_upsample,
371 | use_scale_shift_norm,
372 | dropout,
373 | resblock_updown,
374 | use_fp16,
375 | ):
376 | _ = small_size # hack to prevent unused variable
377 |
378 | if large_size == 512:
379 | channel_mult = (1, 1, 2, 2, 4, 4)
380 | elif large_size == 256:
381 | channel_mult = (1, 1, 2, 2, 4, 4)
382 | elif large_size == 64:
383 | channel_mult = (1, 2, 3, 4)
384 | else:
385 | raise ValueError(f"unsupported large size: {large_size}")
386 |
387 | attention_ds = []
388 | for res in attention_resolutions.split(","):
389 | attention_ds.append(large_size // int(res))
390 |
391 | return SuperResModel(
392 | image_size=large_size,
393 | in_channels=3,
394 | model_channels=num_channels,
395 | out_channels=(3 if not learn_sigma else 6),
396 | num_res_blocks=num_res_blocks,
397 | attention_resolutions=tuple(attention_ds),
398 | dropout=dropout,
399 | channel_mult=channel_mult,
400 | num_classes=(NUM_CLASSES if class_cond else None),
401 | use_checkpoint=use_checkpoint,
402 | num_heads=num_heads,
403 | num_head_channels=num_head_channels,
404 | num_heads_upsample=num_heads_upsample,
405 | use_scale_shift_norm=use_scale_shift_norm,
406 | resblock_updown=resblock_updown,
407 | use_fp16=use_fp16,
408 | )
409 |
410 |
411 | def create_gaussian_diffusion(
412 | *,
413 | steps=1000,
414 | learn_sigma=False,
415 | sigma_small=False,
416 | noise_schedule="linear",
417 | use_kl=False,
418 | predict_xstart=False,
419 | rescale_timesteps=False,
420 | rescale_learned_sigmas=False,
421 | timestep_respacing="",
422 | sel_attn_block=None,
423 | sel_attn_depth=None,
424 | num_heads=None,
425 | ):
426 | betas = gd.get_named_beta_schedule(noise_schedule, steps)
427 | if use_kl:
428 | loss_type = gd.LossType.RESCALED_KL
429 | elif rescale_learned_sigmas:
430 | loss_type = gd.LossType.RESCALED_MSE
431 | else:
432 | loss_type = gd.LossType.MSE
433 | if not timestep_respacing:
434 | timestep_respacing = [steps]
435 | return SpacedDiffusion(
436 | use_timesteps=space_timesteps(steps, timestep_respacing),
437 | betas=betas,
438 | model_mean_type=(
439 | gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X
440 | ),
441 | model_var_type=(
442 | (
443 | gd.ModelVarType.FIXED_LARGE
444 | if not sigma_small
445 | else gd.ModelVarType.FIXED_SMALL
446 | )
447 | if not learn_sigma
448 | else gd.ModelVarType.LEARNED_RANGE
449 | ),
450 | loss_type=loss_type,
451 | rescale_timesteps=rescale_timesteps,
452 | sel_attn_block=sel_attn_block,
453 | sel_attn_depth=sel_attn_depth,
454 | num_heads=num_heads,
455 | )
456 |
457 |
458 | def add_dict_to_argparser(parser, default_dict):
459 | for k, v in default_dict.items():
460 | v_type = type(v)
461 | if v is None:
462 | v_type = str
463 | elif isinstance(v, bool):
464 | v_type = str2bool
465 | parser.add_argument(f"--{k}", default=v, type=v_type)
466 |
467 |
468 | def args_to_dict(args, keys):
469 | return {k: getattr(args, k) for k in keys}
470 |
471 |
472 | def str2bool(v):
473 | """
474 | https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
475 | """
476 | if isinstance(v, bool):
477 | return v
478 | if v.lower() in ("yes", "true", "t", "y", "1"):
479 | return True
480 | elif v.lower() in ("no", "false", "f", "n", "0"):
481 | return False
482 | else:
483 | raise argparse.ArgumentTypeError("boolean value expected")
484 |
--------------------------------------------------------------------------------
/guided_diffusion/logger.py:
--------------------------------------------------------------------------------
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 |
496 |
--------------------------------------------------------------------------------
/evaluations/evaluator.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import io
3 | import os
4 | import random
5 | import warnings
6 | import zipfile
7 | from abc import ABC, abstractmethod
8 | from contextlib import contextmanager
9 | from functools import partial
10 | from multiprocessing import cpu_count
11 | from multiprocessing.pool import ThreadPool
12 | from typing import Iterable, Optional, Tuple
13 |
14 | import numpy as np
15 | import requests
16 | import tensorflow.compat.v1 as tf
17 | from scipy import linalg
18 | from tqdm.auto import tqdm
19 |
20 | INCEPTION_V3_URL = "https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/classify_image_graph_def.pb"
21 | INCEPTION_V3_PATH = "classify_image_graph_def.pb"
22 |
23 | FID_POOL_NAME = "pool_3:0"
24 | FID_SPATIAL_NAME = "mixed_6/conv:0"
25 |
26 |
27 | def main():
28 | parser = argparse.ArgumentParser()
29 | parser.add_argument("ref_batch", help="path to reference batch npz file")
30 | parser.add_argument("sample_batch", help="path to sample batch npz file")
31 | args = parser.parse_args()
32 |
33 | config = tf.ConfigProto(
34 | allow_soft_placement=True # allows DecodeJpeg to run on CPU in Inception graph
35 | )
36 | config.gpu_options.allow_growth = True
37 | evaluator = Evaluator(tf.Session(config=config))
38 |
39 | print("warming up TensorFlow...")
40 | # This will cause TF to print a bunch of verbose stuff now rather
41 | # than after the next print(), to help prevent confusion.
42 | evaluator.warmup()
43 |
44 | print("computing reference batch activations...")
45 | ref_acts = evaluator.read_activations(args.ref_batch)
46 | print("computing/reading reference batch statistics...")
47 | ref_stats, ref_stats_spatial = evaluator.read_statistics(args.ref_batch, ref_acts)
48 |
49 | print("computing sample batch activations...")
50 | sample_acts = evaluator.read_activations(args.sample_batch)
51 | print("computing/reading sample batch statistics...")
52 | sample_stats, sample_stats_spatial = evaluator.read_statistics(args.sample_batch, sample_acts)
53 |
54 | print("Computing evaluations...")
55 | print("Inception Score:", evaluator.compute_inception_score(sample_acts[0]))
56 | print("FID:", sample_stats.frechet_distance(ref_stats))
57 | print("sFID:", sample_stats_spatial.frechet_distance(ref_stats_spatial))
58 | prec, recall = evaluator.compute_prec_recall(ref_acts[0], sample_acts[0])
59 | print("Precision:", prec)
60 | print("Recall:", recall)
61 |
62 |
63 | class InvalidFIDException(Exception):
64 | pass
65 |
66 |
67 | class FIDStatistics:
68 | def __init__(self, mu: np.ndarray, sigma: np.ndarray):
69 | self.mu = mu
70 | self.sigma = sigma
71 |
72 | def frechet_distance(self, other, eps=1e-6):
73 | """
74 | Compute the Frechet distance between two sets of statistics.
75 | """
76 | # https://github.com/bioinf-jku/TTUR/blob/73ab375cdf952a12686d9aa7978567771084da42/fid.py#L132
77 | mu1, sigma1 = self.mu, self.sigma
78 | mu2, sigma2 = other.mu, other.sigma
79 |
80 | mu1 = np.atleast_1d(mu1)
81 | mu2 = np.atleast_1d(mu2)
82 |
83 | sigma1 = np.atleast_2d(sigma1)
84 | sigma2 = np.atleast_2d(sigma2)
85 |
86 | assert (
87 | mu1.shape == mu2.shape
88 | ), f"Training and test mean vectors have different lengths: {mu1.shape}, {mu2.shape}"
89 | assert (
90 | sigma1.shape == sigma2.shape
91 | ), f"Training and test covariances have different dimensions: {sigma1.shape}, {sigma2.shape}"
92 |
93 | diff = mu1 - mu2
94 |
95 | # product might be almost singular
96 | covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
97 | if not np.isfinite(covmean).all():
98 | msg = (
99 | "fid calculation produces singular product; adding %s to diagonal of cov estimates"
100 | % eps
101 | )
102 | warnings.warn(msg)
103 | offset = np.eye(sigma1.shape[0]) * eps
104 | covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
105 |
106 | # numerical error might give slight imaginary component
107 | if np.iscomplexobj(covmean):
108 | if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
109 | m = np.max(np.abs(covmean.imag))
110 | raise ValueError("Imaginary component {}".format(m))
111 | covmean = covmean.real
112 |
113 | tr_covmean = np.trace(covmean)
114 |
115 | return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean
116 |
117 |
118 | class Evaluator:
119 | def __init__(
120 | self,
121 | session,
122 | batch_size=64,
123 | softmax_batch_size=512,
124 | ):
125 | self.sess = session
126 | self.batch_size = batch_size
127 | self.softmax_batch_size = softmax_batch_size
128 | self.manifold_estimator = ManifoldEstimator(session)
129 | with self.sess.graph.as_default():
130 | self.image_input = tf.placeholder(tf.float32, shape=[None, None, None, 3])
131 | self.softmax_input = tf.placeholder(tf.float32, shape=[None, 2048])
132 | self.pool_features, self.spatial_features = _create_feature_graph(self.image_input)
133 | self.softmax = _create_softmax_graph(self.softmax_input)
134 |
135 | def warmup(self):
136 | self.compute_activations(np.zeros([1, 8, 64, 64, 3]))
137 |
138 | def read_activations(self, npz_path: str) -> Tuple[np.ndarray, np.ndarray]:
139 | with open_npz_array(npz_path, "arr_0") as reader:
140 | return self.compute_activations(reader.read_batches(self.batch_size))
141 |
142 | def compute_activations(self, batches: Iterable[np.ndarray]) -> Tuple[np.ndarray, np.ndarray]:
143 | """
144 | Compute image features for downstream evals.
145 |
146 | :param batches: a iterator over NHWC numpy arrays in [0, 255].
147 | :return: a tuple of numpy arrays of shape [N x X], where X is a feature
148 | dimension. The tuple is (pool_3, spatial).
149 | """
150 | preds = []
151 | spatial_preds = []
152 | for batch in tqdm(batches):
153 | batch = batch.astype(np.float32)
154 | pred, spatial_pred = self.sess.run(
155 | [self.pool_features, self.spatial_features], {self.image_input: batch}
156 | )
157 | preds.append(pred.reshape([pred.shape[0], -1]))
158 | spatial_preds.append(spatial_pred.reshape([spatial_pred.shape[0], -1]))
159 | return (
160 | np.concatenate(preds, axis=0),
161 | np.concatenate(spatial_preds, axis=0),
162 | )
163 |
164 | def read_statistics(
165 | self, npz_path: str, activations: Tuple[np.ndarray, np.ndarray]
166 | ) -> Tuple[FIDStatistics, FIDStatistics]:
167 | obj = np.load(npz_path)
168 | if "mu" in list(obj.keys()):
169 | return FIDStatistics(obj["mu"], obj["sigma"]), FIDStatistics(
170 | obj["mu_s"], obj["sigma_s"]
171 | )
172 | return tuple(self.compute_statistics(x) for x in activations)
173 |
174 | def compute_statistics(self, activations: np.ndarray) -> FIDStatistics:
175 | mu = np.mean(activations, axis=0)
176 | sigma = np.cov(activations, rowvar=False)
177 | return FIDStatistics(mu, sigma)
178 |
179 | def compute_inception_score(self, activations: np.ndarray, split_size: int = 5000) -> float:
180 | softmax_out = []
181 | for i in range(0, len(activations), self.softmax_batch_size):
182 | acts = activations[i : i + self.softmax_batch_size]
183 | softmax_out.append(self.sess.run(self.softmax, feed_dict={self.softmax_input: acts}))
184 | preds = np.concatenate(softmax_out, axis=0)
185 | # https://github.com/openai/improved-gan/blob/4f5d1ec5c16a7eceb206f42bfc652693601e1d5c/inception_score/model.py#L46
186 | scores = []
187 | for i in range(0, len(preds), split_size):
188 | part = preds[i : i + split_size]
189 | kl = part * (np.log(part) - np.log(np.expand_dims(np.mean(part, 0), 0)))
190 | kl = np.mean(np.sum(kl, 1))
191 | scores.append(np.exp(kl))
192 | return float(np.mean(scores))
193 |
194 | def compute_prec_recall(
195 | self, activations_ref: np.ndarray, activations_sample: np.ndarray
196 | ) -> Tuple[float, float]:
197 | radii_1 = self.manifold_estimator.manifold_radii(activations_ref)
198 | radii_2 = self.manifold_estimator.manifold_radii(activations_sample)
199 | pr = self.manifold_estimator.evaluate_pr(
200 | activations_ref, radii_1, activations_sample, radii_2
201 | )
202 | return (float(pr[0][0]), float(pr[1][0]))
203 |
204 |
205 | class ManifoldEstimator:
206 | """
207 | A helper for comparing manifolds of feature vectors.
208 |
209 | Adapted from https://github.com/kynkaat/improved-precision-and-recall-metric/blob/f60f25e5ad933a79135c783fcda53de30f42c9b9/precision_recall.py#L57
210 | """
211 |
212 | def __init__(
213 | self,
214 | session,
215 | row_batch_size=10000,
216 | col_batch_size=10000,
217 | nhood_sizes=(3,),
218 | clamp_to_percentile=None,
219 | eps=1e-5,
220 | ):
221 | """
222 | Estimate the manifold of given feature vectors.
223 |
224 | :param session: the TensorFlow session.
225 | :param row_batch_size: row batch size to compute pairwise distances
226 | (parameter to trade-off between memory usage and performance).
227 | :param col_batch_size: column batch size to compute pairwise distances.
228 | :param nhood_sizes: number of neighbors used to estimate the manifold.
229 | :param clamp_to_percentile: prune hyperspheres that have radius larger than
230 | the given percentile.
231 | :param eps: small number for numerical stability.
232 | """
233 | self.distance_block = DistanceBlock(session)
234 | self.row_batch_size = row_batch_size
235 | self.col_batch_size = col_batch_size
236 | self.nhood_sizes = nhood_sizes
237 | self.num_nhoods = len(nhood_sizes)
238 | self.clamp_to_percentile = clamp_to_percentile
239 | self.eps = eps
240 |
241 | def warmup(self):
242 | feats, radii = (
243 | np.zeros([1, 2048], dtype=np.float32),
244 | np.zeros([1, 1], dtype=np.float32),
245 | )
246 | self.evaluate_pr(feats, radii, feats, radii)
247 |
248 | def manifold_radii(self, features: np.ndarray) -> np.ndarray:
249 | num_images = len(features)
250 |
251 | # Estimate manifold of features by calculating distances to k-NN of each sample.
252 | radii = np.zeros([num_images, self.num_nhoods], dtype=np.float32)
253 | distance_batch = np.zeros([self.row_batch_size, num_images], dtype=np.float32)
254 | seq = np.arange(max(self.nhood_sizes) + 1, dtype=np.int32)
255 |
256 | for begin1 in range(0, num_images, self.row_batch_size):
257 | end1 = min(begin1 + self.row_batch_size, num_images)
258 | row_batch = features[begin1:end1]
259 |
260 | for begin2 in range(0, num_images, self.col_batch_size):
261 | end2 = min(begin2 + self.col_batch_size, num_images)
262 | col_batch = features[begin2:end2]
263 |
264 | # Compute distances between batches.
265 | distance_batch[
266 | 0 : end1 - begin1, begin2:end2
267 | ] = self.distance_block.pairwise_distances(row_batch, col_batch)
268 |
269 | # Find the k-nearest neighbor from the current batch.
270 | radii[begin1:end1, :] = np.concatenate(
271 | [
272 | x[:, self.nhood_sizes]
273 | for x in _numpy_partition(distance_batch[0 : end1 - begin1, :], seq, axis=1)
274 | ],
275 | axis=0,
276 | )
277 |
278 | if self.clamp_to_percentile is not None:
279 | max_distances = np.percentile(radii, self.clamp_to_percentile, axis=0)
280 | radii[radii > max_distances] = 0
281 | return radii
282 |
283 | def evaluate(self, features: np.ndarray, radii: np.ndarray, eval_features: np.ndarray):
284 | """
285 | Evaluate if new feature vectors are at the manifold.
286 | """
287 | num_eval_images = eval_features.shape[0]
288 | num_ref_images = radii.shape[0]
289 | distance_batch = np.zeros([self.row_batch_size, num_ref_images], dtype=np.float32)
290 | batch_predictions = np.zeros([num_eval_images, self.num_nhoods], dtype=np.int32)
291 | max_realism_score = np.zeros([num_eval_images], dtype=np.float32)
292 | nearest_indices = np.zeros([num_eval_images], dtype=np.int32)
293 |
294 | for begin1 in range(0, num_eval_images, self.row_batch_size):
295 | end1 = min(begin1 + self.row_batch_size, num_eval_images)
296 | feature_batch = eval_features[begin1:end1]
297 |
298 | for begin2 in range(0, num_ref_images, self.col_batch_size):
299 | end2 = min(begin2 + self.col_batch_size, num_ref_images)
300 | ref_batch = features[begin2:end2]
301 |
302 | distance_batch[
303 | 0 : end1 - begin1, begin2:end2
304 | ] = self.distance_block.pairwise_distances(feature_batch, ref_batch)
305 |
306 | # From the minibatch of new feature vectors, determine if they are in the estimated manifold.
307 | # If a feature vector is inside a hypersphere of some reference sample, then
308 | # the new sample lies at the estimated manifold.
309 | # The radii of the hyperspheres are determined from distances of neighborhood size k.
310 | samples_in_manifold = distance_batch[0 : end1 - begin1, :, None] <= radii
311 | batch_predictions[begin1:end1] = np.any(samples_in_manifold, axis=1).astype(np.int32)
312 |
313 | max_realism_score[begin1:end1] = np.max(
314 | radii[:, 0] / (distance_batch[0 : end1 - begin1, :] + self.eps), axis=1
315 | )
316 | nearest_indices[begin1:end1] = np.argmin(distance_batch[0 : end1 - begin1, :], axis=1)
317 |
318 | return {
319 | "fraction": float(np.mean(batch_predictions)),
320 | "batch_predictions": batch_predictions,
321 | "max_realisim_score": max_realism_score,
322 | "nearest_indices": nearest_indices,
323 | }
324 |
325 | def evaluate_pr(
326 | self,
327 | features_1: np.ndarray,
328 | radii_1: np.ndarray,
329 | features_2: np.ndarray,
330 | radii_2: np.ndarray,
331 | ) -> Tuple[np.ndarray, np.ndarray]:
332 | """
333 | Evaluate precision and recall efficiently.
334 |
335 | :param features_1: [N1 x D] feature vectors for reference batch.
336 | :param radii_1: [N1 x K1] radii for reference vectors.
337 | :param features_2: [N2 x D] feature vectors for the other batch.
338 | :param radii_2: [N x K2] radii for other vectors.
339 | :return: a tuple of arrays for (precision, recall):
340 | - precision: an np.ndarray of length K1
341 | - recall: an np.ndarray of length K2
342 | """
343 | features_1_status = np.zeros([len(features_1), radii_2.shape[1]], dtype=np.bool)
344 | features_2_status = np.zeros([len(features_2), radii_1.shape[1]], dtype=np.bool)
345 | for begin_1 in range(0, len(features_1), self.row_batch_size):
346 | end_1 = begin_1 + self.row_batch_size
347 | batch_1 = features_1[begin_1:end_1]
348 | for begin_2 in range(0, len(features_2), self.col_batch_size):
349 | end_2 = begin_2 + self.col_batch_size
350 | batch_2 = features_2[begin_2:end_2]
351 | batch_1_in, batch_2_in = self.distance_block.less_thans(
352 | batch_1, radii_1[begin_1:end_1], batch_2, radii_2[begin_2:end_2]
353 | )
354 | features_1_status[begin_1:end_1] |= batch_1_in
355 | features_2_status[begin_2:end_2] |= batch_2_in
356 | return (
357 | np.mean(features_2_status.astype(np.float64), axis=0),
358 | np.mean(features_1_status.astype(np.float64), axis=0),
359 | )
360 |
361 |
362 | class DistanceBlock:
363 | """
364 | Calculate pairwise distances between vectors.
365 |
366 | Adapted from https://github.com/kynkaat/improved-precision-and-recall-metric/blob/f60f25e5ad933a79135c783fcda53de30f42c9b9/precision_recall.py#L34
367 | """
368 |
369 | def __init__(self, session):
370 | self.session = session
371 |
372 | # Initialize TF graph to calculate pairwise distances.
373 | with session.graph.as_default():
374 | self._features_batch1 = tf.placeholder(tf.float32, shape=[None, None])
375 | self._features_batch2 = tf.placeholder(tf.float32, shape=[None, None])
376 | distance_block_16 = _batch_pairwise_distances(
377 | tf.cast(self._features_batch1, tf.float16),
378 | tf.cast(self._features_batch2, tf.float16),
379 | )
380 | self.distance_block = tf.cond(
381 | tf.reduce_all(tf.math.is_finite(distance_block_16)),
382 | lambda: tf.cast(distance_block_16, tf.float32),
383 | lambda: _batch_pairwise_distances(self._features_batch1, self._features_batch2),
384 | )
385 |
386 | # Extra logic for less thans.
387 | self._radii1 = tf.placeholder(tf.float32, shape=[None, None])
388 | self._radii2 = tf.placeholder(tf.float32, shape=[None, None])
389 | dist32 = tf.cast(self.distance_block, tf.float32)[..., None]
390 | self._batch_1_in = tf.math.reduce_any(dist32 <= self._radii2, axis=1)
391 | self._batch_2_in = tf.math.reduce_any(dist32 <= self._radii1[:, None], axis=0)
392 |
393 | def pairwise_distances(self, U, V):
394 | """
395 | Evaluate pairwise distances between two batches of feature vectors.
396 | """
397 | return self.session.run(
398 | self.distance_block,
399 | feed_dict={self._features_batch1: U, self._features_batch2: V},
400 | )
401 |
402 | def less_thans(self, batch_1, radii_1, batch_2, radii_2):
403 | return self.session.run(
404 | [self._batch_1_in, self._batch_2_in],
405 | feed_dict={
406 | self._features_batch1: batch_1,
407 | self._features_batch2: batch_2,
408 | self._radii1: radii_1,
409 | self._radii2: radii_2,
410 | },
411 | )
412 |
413 |
414 | def _batch_pairwise_distances(U, V):
415 | """
416 | Compute pairwise distances between two batches of feature vectors.
417 | """
418 | with tf.variable_scope("pairwise_dist_block"):
419 | # Squared norms of each row in U and V.
420 | norm_u = tf.reduce_sum(tf.square(U), 1)
421 | norm_v = tf.reduce_sum(tf.square(V), 1)
422 |
423 | # norm_u as a column and norm_v as a row vectors.
424 | norm_u = tf.reshape(norm_u, [-1, 1])
425 | norm_v = tf.reshape(norm_v, [1, -1])
426 |
427 | # Pairwise squared Euclidean distances.
428 | D = tf.maximum(norm_u - 2 * tf.matmul(U, V, False, True) + norm_v, 0.0)
429 |
430 | return D
431 |
432 |
433 | class NpzArrayReader(ABC):
434 | @abstractmethod
435 | def read_batch(self, batch_size: int) -> Optional[np.ndarray]:
436 | pass
437 |
438 | @abstractmethod
439 | def remaining(self) -> int:
440 | pass
441 |
442 | def read_batches(self, batch_size: int) -> Iterable[np.ndarray]:
443 | def gen_fn():
444 | while True:
445 | batch = self.read_batch(batch_size)
446 | if batch is None:
447 | break
448 | yield batch
449 |
450 | rem = self.remaining()
451 | num_batches = rem // batch_size + int(rem % batch_size != 0)
452 | return BatchIterator(gen_fn, num_batches)
453 |
454 |
455 | class BatchIterator:
456 | def __init__(self, gen_fn, length):
457 | self.gen_fn = gen_fn
458 | self.length = length
459 |
460 | def __len__(self):
461 | return self.length
462 |
463 | def __iter__(self):
464 | return self.gen_fn()
465 |
466 |
467 | class StreamingNpzArrayReader(NpzArrayReader):
468 | def __init__(self, arr_f, shape, dtype):
469 | self.arr_f = arr_f
470 | self.shape = shape
471 | self.dtype = dtype
472 | self.idx = 0
473 |
474 | def read_batch(self, batch_size: int) -> Optional[np.ndarray]:
475 | if self.idx >= self.shape[0]:
476 | return None
477 |
478 | bs = min(batch_size, self.shape[0] - self.idx)
479 | self.idx += bs
480 |
481 | if self.dtype.itemsize == 0:
482 | return np.ndarray([bs, *self.shape[1:]], dtype=self.dtype)
483 |
484 | read_count = bs * np.prod(self.shape[1:])
485 | read_size = int(read_count * self.dtype.itemsize)
486 | data = _read_bytes(self.arr_f, read_size, "array data")
487 | return np.frombuffer(data, dtype=self.dtype).reshape([bs, *self.shape[1:]])
488 |
489 | def remaining(self) -> int:
490 | return max(0, self.shape[0] - self.idx)
491 |
492 |
493 | class MemoryNpzArrayReader(NpzArrayReader):
494 | def __init__(self, arr):
495 | self.arr = arr
496 | self.idx = 0
497 |
498 | @classmethod
499 | def load(cls, path: str, arr_name: str):
500 | with open(path, "rb") as f:
501 | arr = np.load(f)[arr_name]
502 | return cls(arr)
503 |
504 | def read_batch(self, batch_size: int) -> Optional[np.ndarray]:
505 | if self.idx >= self.arr.shape[0]:
506 | return None
507 |
508 | res = self.arr[self.idx : self.idx + batch_size]
509 | self.idx += batch_size
510 | return res
511 |
512 | def remaining(self) -> int:
513 | return max(0, self.arr.shape[0] - self.idx)
514 |
515 |
516 | @contextmanager
517 | def open_npz_array(path: str, arr_name: str) -> NpzArrayReader:
518 | with _open_npy_file(path, arr_name) as arr_f:
519 | version = np.lib.format.read_magic(arr_f)
520 | if version == (1, 0):
521 | header = np.lib.format.read_array_header_1_0(arr_f)
522 | elif version == (2, 0):
523 | header = np.lib.format.read_array_header_2_0(arr_f)
524 | else:
525 | yield MemoryNpzArrayReader.load(path, arr_name)
526 | return
527 | shape, fortran, dtype = header
528 | if fortran or dtype.hasobject:
529 | yield MemoryNpzArrayReader.load(path, arr_name)
530 | else:
531 | yield StreamingNpzArrayReader(arr_f, shape, dtype)
532 |
533 |
534 | def _read_bytes(fp, size, error_template="ran out of data"):
535 | """
536 | Copied from: https://github.com/numpy/numpy/blob/fb215c76967739268de71aa4bda55dd1b062bc2e/numpy/lib/format.py#L788-L886
537 |
538 | Read from file-like object until size bytes are read.
539 | Raises ValueError if not EOF is encountered before size bytes are read.
540 | Non-blocking objects only supported if they derive from io objects.
541 | Required as e.g. ZipExtFile in python 2.6 can return less data than
542 | requested.
543 | """
544 | data = bytes()
545 | while True:
546 | # io files (default in python3) return None or raise on
547 | # would-block, python2 file will truncate, probably nothing can be
548 | # done about that. note that regular files can't be non-blocking
549 | try:
550 | r = fp.read(size - len(data))
551 | data += r
552 | if len(r) == 0 or len(data) == size:
553 | break
554 | except io.BlockingIOError:
555 | pass
556 | if len(data) != size:
557 | msg = "EOF: reading %s, expected %d bytes got %d"
558 | raise ValueError(msg % (error_template, size, len(data)))
559 | else:
560 | return data
561 |
562 |
563 | @contextmanager
564 | def _open_npy_file(path: str, arr_name: str):
565 | with open(path, "rb") as f:
566 | with zipfile.ZipFile(f, "r") as zip_f:
567 | if f"{arr_name}.npy" not in zip_f.namelist():
568 | raise ValueError(f"missing {arr_name} in npz file")
569 | with zip_f.open(f"{arr_name}.npy", "r") as arr_f:
570 | yield arr_f
571 |
572 |
573 | def _download_inception_model():
574 | if os.path.exists(INCEPTION_V3_PATH):
575 | return
576 | print("downloading InceptionV3 model...")
577 | with requests.get(INCEPTION_V3_URL, stream=True) as r:
578 | r.raise_for_status()
579 | tmp_path = INCEPTION_V3_PATH + ".tmp"
580 | with open(tmp_path, "wb") as f:
581 | for chunk in tqdm(r.iter_content(chunk_size=8192)):
582 | f.write(chunk)
583 | os.rename(tmp_path, INCEPTION_V3_PATH)
584 |
585 |
586 | def _create_feature_graph(input_batch):
587 | _download_inception_model()
588 | prefix = f"{random.randrange(2**32)}_{random.randrange(2**32)}"
589 | with open(INCEPTION_V3_PATH, "rb") as f:
590 | graph_def = tf.GraphDef()
591 | graph_def.ParseFromString(f.read())
592 | pool3, spatial = tf.import_graph_def(
593 | graph_def,
594 | input_map={f"ExpandDims:0": input_batch},
595 | return_elements=[FID_POOL_NAME, FID_SPATIAL_NAME],
596 | name=prefix,
597 | )
598 | _update_shapes(pool3)
599 | spatial = spatial[..., :7]
600 | return pool3, spatial
601 |
602 |
603 | def _create_softmax_graph(input_batch):
604 | _download_inception_model()
605 | prefix = f"{random.randrange(2**32)}_{random.randrange(2**32)}"
606 | with open(INCEPTION_V3_PATH, "rb") as f:
607 | graph_def = tf.GraphDef()
608 | graph_def.ParseFromString(f.read())
609 | (matmul,) = tf.import_graph_def(
610 | graph_def, return_elements=[f"softmax/logits/MatMul"], name=prefix
611 | )
612 | w = matmul.inputs[1]
613 | logits = tf.matmul(input_batch, w)
614 | return tf.nn.softmax(logits)
615 |
616 |
617 | def _update_shapes(pool3):
618 | # https://github.com/bioinf-jku/TTUR/blob/73ab375cdf952a12686d9aa7978567771084da42/fid.py#L50-L63
619 | ops = pool3.graph.get_operations()
620 | for op in ops:
621 | for o in op.outputs:
622 | shape = o.get_shape()
623 | if shape._dims is not None: # pylint: disable=protected-access
624 | # shape = [s.value for s in shape] TF 1.x
625 | shape = [s for s in shape] # TF 2.x
626 | new_shape = []
627 | for j, s in enumerate(shape):
628 | if s == 1 and j == 0:
629 | new_shape.append(None)
630 | else:
631 | new_shape.append(s)
632 | o.__dict__["_shape_val"] = tf.TensorShape(new_shape)
633 | return pool3
634 |
635 |
636 | def _numpy_partition(arr, kth, **kwargs):
637 | num_workers = min(cpu_count(), len(arr))
638 | chunk_size = len(arr) // num_workers
639 | extra = len(arr) % num_workers
640 |
641 | start_idx = 0
642 | batches = []
643 | for i in range(num_workers):
644 | size = chunk_size + (1 if i < extra else 0)
645 | batches.append(arr[start_idx : start_idx + size])
646 | start_idx += size
647 |
648 | with ThreadPool(num_workers) as pool:
649 | return list(pool.map(partial(np.partition, kth=kth, **kwargs), batches))
650 |
651 |
652 | if __name__ == "__main__":
653 | main()
654 |
--------------------------------------------------------------------------------
/guided_diffusion/unet.py:
--------------------------------------------------------------------------------
1 | import math
2 | from abc import abstractmethod
3 |
4 | import numpy as np
5 | import torch as th
6 | import torch.nn as nn
7 | import torch.nn.functional as F
8 |
9 | from .fp16_util import convert_module_to_f16, convert_module_to_f32
10 | from .nn import (avg_pool_nd, checkpoint, conv_nd, linear, normalization,
11 | timestep_embedding, zero_module)
12 |
13 |
14 | class AttentionPool2d(nn.Module):
15 | """
16 | Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
17 | """
18 |
19 | def __init__(
20 | self,
21 | spacial_dim: int,
22 | embed_dim: int,
23 | num_heads_channels: int,
24 | output_dim: int = None,
25 | ):
26 | super().__init__()
27 | self.positional_embedding = nn.Parameter(
28 | th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5
29 | )
30 | self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
31 | self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
32 | self.num_heads = embed_dim // num_heads_channels
33 | self.attention = QKVAttention(self.num_heads)
34 |
35 | def forward(self, x):
36 | b, c, *_spatial = x.shape
37 | x = x.reshape(b, c, -1) # NC(HW)
38 | x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
39 | x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
40 | x = self.qkv_proj(x)
41 | x = self.attention(x)
42 | x = self.c_proj(x)
43 | return x[:, :, 0]
44 |
45 |
46 | class TimestepBlock(nn.Module):
47 | """
48 | Any module where forward() takes timestep embeddings as a second argument.
49 | """
50 |
51 | @abstractmethod
52 | def forward(self, x, emb):
53 | """
54 | Apply the module to `x` given `emb` timestep embeddings.
55 | """
56 |
57 |
58 | class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
59 | """
60 | A sequential module that passes timestep embeddings to the children that
61 | support it as an extra input.
62 | """
63 |
64 | def forward(self, x, emb):
65 | for layer in self:
66 | if isinstance(layer, TimestepBlock):
67 | x = layer(x, emb)
68 | else:
69 | x = layer(x)
70 | return x
71 |
72 |
73 | class Upsample(nn.Module):
74 | """
75 | An upsampling layer with an optional convolution.
76 |
77 | :param channels: channels in the inputs and outputs.
78 | :param use_conv: a bool determining if a convolution is applied.
79 | :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
80 | upsampling occurs in the inner-two dimensions.
81 | """
82 |
83 | def __init__(self, channels, use_conv, dims=2, out_channels=None):
84 | super().__init__()
85 | self.channels = channels
86 | self.out_channels = out_channels or channels
87 | self.use_conv = use_conv
88 | self.dims = dims
89 | if use_conv:
90 | self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
91 |
92 | def forward(self, x):
93 | assert x.shape[1] == self.channels
94 | if self.dims == 3:
95 | x = F.interpolate(
96 | x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
97 | )
98 | else:
99 | x = F.interpolate(x, scale_factor=2, mode="nearest")
100 | if self.use_conv:
101 | x = self.conv(x)
102 | return x
103 |
104 |
105 | class Downsample(nn.Module):
106 | """
107 | A downsampling layer with an optional convolution.
108 |
109 | :param channels: channels in the inputs and outputs.
110 | :param use_conv: a bool determining if a convolution is applied.
111 | :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
112 | downsampling occurs in the inner-two dimensions.
113 | """
114 |
115 | def __init__(self, channels, use_conv, dims=2, out_channels=None):
116 | super().__init__()
117 | self.channels = channels
118 | self.out_channels = out_channels or channels
119 | self.use_conv = use_conv
120 | self.dims = dims
121 | stride = 2 if dims != 3 else (1, 2, 2)
122 | if use_conv:
123 | self.op = conv_nd(
124 | dims, self.channels, self.out_channels, 3, stride=stride, padding=1
125 | )
126 | else:
127 | assert self.channels == self.out_channels
128 | self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
129 |
130 | def forward(self, x):
131 | assert x.shape[1] == self.channels
132 | return self.op(x)
133 |
134 |
135 | class ResBlock(TimestepBlock):
136 | """
137 | A residual block that can optionally change the number of channels.
138 |
139 | :param channels: the number of input channels.
140 | :param emb_channels: the number of timestep embedding channels.
141 | :param dropout: the rate of dropout.
142 | :param out_channels: if specified, the number of out channels.
143 | :param use_conv: if True and out_channels is specified, use a spatial
144 | convolution instead of a smaller 1x1 convolution to change the
145 | channels in the skip connection.
146 | :param dims: determines if the signal is 1D, 2D, or 3D.
147 | :param use_checkpoint: if True, use gradient checkpointing on this module.
148 | :param up: if True, use this block for upsampling.
149 | :param down: if True, use this block for downsampling.
150 | """
151 |
152 | def __init__(
153 | self,
154 | channels,
155 | emb_channels,
156 | dropout,
157 | out_channels=None,
158 | use_conv=False,
159 | use_scale_shift_norm=False,
160 | dims=2,
161 | use_checkpoint=False,
162 | up=False,
163 | down=False,
164 | ):
165 | super().__init__()
166 | self.channels = channels
167 | self.emb_channels = emb_channels
168 | self.dropout = dropout
169 | self.out_channels = out_channels or channels
170 | self.use_conv = use_conv
171 | self.use_checkpoint = use_checkpoint
172 | self.use_scale_shift_norm = use_scale_shift_norm
173 |
174 | self.in_layers = nn.Sequential(
175 | normalization(channels),
176 | nn.SiLU(),
177 | conv_nd(dims, channels, self.out_channels, 3, padding=1),
178 | )
179 |
180 | self.updown = up or down
181 |
182 | if up:
183 | self.h_upd = Upsample(channels, False, dims)
184 | self.x_upd = Upsample(channels, False, dims)
185 | elif down:
186 | self.h_upd = Downsample(channels, False, dims)
187 | self.x_upd = Downsample(channels, False, dims)
188 | else:
189 | self.h_upd = self.x_upd = nn.Identity()
190 |
191 | self.emb_layers = nn.Sequential(
192 | nn.SiLU(),
193 | linear(
194 | emb_channels,
195 | 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
196 | ),
197 | )
198 | self.out_layers = nn.Sequential(
199 | normalization(self.out_channels),
200 | nn.SiLU(),
201 | nn.Dropout(p=dropout),
202 | zero_module(
203 | conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
204 | ),
205 | )
206 |
207 | if self.out_channels == channels:
208 | self.skip_connection = nn.Identity()
209 | elif use_conv:
210 | self.skip_connection = conv_nd(
211 | dims, channels, self.out_channels, 3, padding=1
212 | )
213 | else:
214 | self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
215 |
216 | def forward(self, x, emb):
217 | """
218 | Apply the block to a Tensor, conditioned on a timestep embedding.
219 |
220 | :param x: an [N x C x ...] Tensor of features.
221 | :param emb: an [N x emb_channels] Tensor of timestep embeddings.
222 | :return: an [N x C x ...] Tensor of outputs.
223 | """
224 | return checkpoint(
225 | self._forward, (x, emb), self.parameters(), self.use_checkpoint
226 | )
227 |
228 | def _forward(self, x, emb):
229 | if self.updown:
230 | in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
231 | h = in_rest(x)
232 | h = self.h_upd(h)
233 | x = self.x_upd(x)
234 | h = in_conv(h)
235 | else:
236 | h = self.in_layers(x)
237 | emb_out = self.emb_layers(emb).type(h.dtype)
238 | while len(emb_out.shape) < len(h.shape):
239 | emb_out = emb_out[..., None]
240 | if self.use_scale_shift_norm:
241 | out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
242 | scale, shift = th.chunk(emb_out, 2, dim=1)
243 | h = out_norm(h) * (1 + scale) + shift
244 | h = out_rest(h)
245 | else:
246 | h = h + emb_out
247 | h = self.out_layers(h)
248 | return self.skip_connection(x) + h
249 |
250 |
251 | class AttentionBlock(nn.Module):
252 | """
253 | An attention block that allows spatial positions to attend to each other.
254 |
255 | Originally ported from here, but adapted to the N-d case.
256 | https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
257 | """
258 |
259 | def __init__(
260 | self,
261 | channels,
262 | num_heads=1,
263 | num_head_channels=-1,
264 | use_checkpoint=False,
265 | use_new_attention_order=False,
266 | ):
267 | super().__init__()
268 | self.channels = channels
269 | if num_head_channels == -1:
270 | self.num_heads = num_heads
271 | else:
272 | assert (
273 | channels % num_head_channels == 0
274 | ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
275 | self.num_heads = channels // num_head_channels
276 | self.use_checkpoint = use_checkpoint
277 | self.norm = normalization(channels)
278 | self.qkv = conv_nd(1, channels, channels * 3, 1)
279 | if use_new_attention_order:
280 | # split qkv before split heads
281 | self.attention = QKVAttention(self.num_heads)
282 | else:
283 | # split heads before split qkv
284 | self.attention = QKVAttentionLegacy(self.num_heads)
285 |
286 | self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
287 |
288 | def forward(self, x):
289 | return checkpoint(self._forward, (x,), self.parameters(), True)
290 |
291 | def _forward(self, x):
292 | b, c, *spatial = x.shape
293 | x = x.reshape(b, c, -1)
294 | qkv = self.qkv(self.norm(x))
295 | h = self.attention(qkv)
296 | h = self.proj_out(h)
297 | return (x + h).reshape(b, c, *spatial)
298 |
299 |
300 | def count_flops_attn(model, _x, y):
301 | """
302 | A counter for the `thop` package to count the operations in an
303 | attention operation.
304 | Meant to be used like:
305 | macs, params = thop.profile(
306 | model,
307 | inputs=(inputs, timestamps),
308 | custom_ops={QKVAttention: QKVAttention.count_flops},
309 | )
310 | """
311 | b, c, *spatial = y[0].shape
312 | num_spatial = int(np.prod(spatial))
313 | # We perform two matmuls with the same number of ops.
314 | # The first computes the weight matrix, the second computes
315 | # the combination of the value vectors.
316 | matmul_ops = 2 * b * (num_spatial ** 2) * c
317 | model.total_ops += th.DoubleTensor([matmul_ops])
318 |
319 |
320 | class QKVAttentionLegacy(nn.Module):
321 | """
322 | A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
323 | """
324 |
325 | def __init__(self, n_heads):
326 | super().__init__()
327 | self.n_heads = n_heads
328 |
329 | def forward(self, qkv):
330 | """
331 | Apply QKV attention.
332 |
333 | :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
334 | :return: an [N x (H * C) x T] tensor after attention.
335 | """
336 | bs, width, length = qkv.shape
337 | assert width % (3 * self.n_heads) == 0
338 | ch = width // (3 * self.n_heads)
339 | q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
340 | scale = 1 / math.sqrt(math.sqrt(ch))
341 | weight = th.einsum(
342 | "bct,bcs->bts", q * scale, k * scale
343 | ) # More stable with f16 than dividing afterwards
344 | weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
345 | a = th.einsum("bts,bcs->bct", weight, v)
346 | return a.reshape(bs, -1, length)
347 |
348 | @staticmethod
349 | def count_flops(model, _x, y):
350 | return count_flops_attn(model, _x, y)
351 |
352 |
353 | class QKVAttention(nn.Module):
354 | """
355 | A module which performs QKV attention and splits in a different order.
356 | """
357 |
358 | def __init__(self, n_heads):
359 | super().__init__()
360 | self.n_heads = n_heads
361 |
362 | def forward(self, qkv):
363 | """
364 | Apply QKV attention.
365 |
366 | :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
367 | :return: an [N x (H * C) x T] tensor after attention.
368 | """
369 | bs, width, length = qkv.shape
370 | assert width % (3 * self.n_heads) == 0
371 | ch = width // (3 * self.n_heads)
372 | q, k, v = qkv.chunk(3, dim=1)
373 | scale = 1 / math.sqrt(math.sqrt(ch))
374 | weight = th.einsum(
375 | "bct,bcs->bts",
376 | (q * scale).view(bs * self.n_heads, ch, length),
377 | (k * scale).view(bs * self.n_heads, ch, length),
378 | ) # More stable with f16 than dividing afterwards
379 | weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
380 | a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
381 | return a.reshape(bs, -1, length)
382 |
383 | @staticmethod
384 | def count_flops(model, _x, y):
385 | return count_flops_attn(model, _x, y)
386 |
387 |
388 | def save_tensors(module: nn.Module, features, name: str):
389 | """ Process and save activations in the module. """
390 | """ From this repository: https://github.com/yandex-research/ddpm-segmentation """
391 | if type(features) in [list, tuple]:
392 | features = [f.detach().float() if f is not None else None
393 | for f in features]
394 | setattr(module, name, features)
395 | elif isinstance(features, dict):
396 | features = {k: f.detach().float() for k, f in features.items()}
397 | setattr(module, name, features)
398 | else:
399 | setattr(module, name, features.detach().float())
400 |
401 |
402 | def save_input_hook(self, inp, out):
403 | save_tensors(self, inp[0], 'qkv')
404 | return out
405 |
406 | def attention_from_qkv(qkv, num_heads):
407 | bs, width, length = qkv.shape
408 | assert width % (3 * num_heads) == 0
409 | ch = width // (3 * num_heads)
410 | q, k, v = qkv.reshape(bs * num_heads, ch * 3, length).split(ch, dim=1)
411 | scale = 1 / math.sqrt(math.sqrt(ch))
412 | weight = th.einsum(
413 | "bct,bcs->bts", q * scale, k * scale
414 | ) # More stable with f16 than dividing afterwards
415 | weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
416 | return weight
417 |
418 |
419 | class UNetModel(nn.Module):
420 | """
421 | The full UNet model with attention and timestep embedding.
422 |
423 | :param in_channels: channels in the input Tensor.
424 | :param model_channels: base channel count for the model.
425 | :param out_channels: channels in the output Tensor.
426 | :param num_res_blocks: number of residual blocks per downsample.
427 | :param attention_resolutions: a collection of downsample rates at which
428 | attention will take place. May be a set, list, or tuple.
429 | For example, if this contains 4, then at 4x downsampling, attention
430 | will be used.
431 | :param dropout: the dropout probability.
432 | :param channel_mult: channel multiplier for each level of the UNet.
433 | :param conv_resample: if True, use learned convolutions for upsampling and
434 | downsampling.
435 | :param dims: determines if the signal is 1D, 2D, or 3D.
436 | :param num_classes: if specified (as an int), then this model will be
437 | class-conditional with `num_classes` classes.
438 | :param use_checkpoint: use gradient checkpointing to reduce memory usage.
439 | :param num_heads: the number of attention heads in each attention layer.
440 | :param num_heads_channels: if specified, ignore num_heads and instead use
441 | a fixed channel width per attention head.
442 | :param num_heads_upsample: works with num_heads to set a different number
443 | of heads for upsampling. Deprecated.
444 | :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
445 | :param resblock_updown: use residual blocks for up/downsampling.
446 | :param use_new_attention_order: use a different attention pattern for potentially
447 | increased efficiency.
448 | :param sel_attn_depth: UNet decoder layer at which attention maps are extracted
449 | :param sel_attn_block: "middle" or "output" of UNet
450 | """
451 |
452 | def __init__(
453 | self,
454 | image_size,
455 | in_channels,
456 | model_channels,
457 | out_channels,
458 | num_res_blocks,
459 | attention_resolutions,
460 | dropout=0,
461 | channel_mult=(1, 2, 4, 8),
462 | conv_resample=True,
463 | dims=2,
464 | num_classes=None,
465 | use_checkpoint=False,
466 | use_fp16=False,
467 | num_heads=1,
468 | num_head_channels=-1,
469 | num_heads_upsample=-1,
470 | use_scale_shift_norm=False,
471 | resblock_updown=False,
472 | use_new_attention_order=False,
473 | sel_attn_depth=2,
474 | sel_attn_block="output"
475 | ):
476 | super().__init__()
477 |
478 | if num_heads_upsample == -1:
479 | num_heads_upsample = num_heads
480 |
481 | self.image_size = image_size
482 | self.in_channels = in_channels
483 | self.model_channels = model_channels
484 | self.out_channels = out_channels
485 | self.num_res_blocks = num_res_blocks
486 | self.attention_resolutions = attention_resolutions
487 | self.dropout = dropout
488 | self.channel_mult = channel_mult
489 | self.conv_resample = conv_resample
490 | self.num_classes = num_classes
491 | self.use_checkpoint = use_checkpoint
492 | self.dtype = th.float16 if use_fp16 else th.float32
493 | self.num_heads = num_heads
494 | self.num_head_channels = num_head_channels
495 | self.num_heads_upsample = num_heads_upsample
496 |
497 | time_embed_dim = model_channels * 4
498 | self.time_embed = nn.Sequential(
499 | linear(model_channels, time_embed_dim),
500 | nn.SiLU(),
501 | linear(time_embed_dim, time_embed_dim),
502 | )
503 |
504 | if self.num_classes is not None:
505 | self.label_emb = nn.Embedding(num_classes, time_embed_dim)
506 |
507 | ch = input_ch = int(channel_mult[0] * model_channels)
508 | self.input_blocks = nn.ModuleList(
509 | [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
510 | )
511 | self._feature_size = ch
512 | input_block_chans = [ch]
513 | ds = 1
514 | for level, mult in enumerate(channel_mult):
515 | for _ in range(num_res_blocks):
516 | layers = [
517 | ResBlock(
518 | ch,
519 | time_embed_dim,
520 | dropout,
521 | out_channels=int(mult * model_channels),
522 | dims=dims,
523 | use_checkpoint=use_checkpoint,
524 | use_scale_shift_norm=use_scale_shift_norm,
525 | )
526 | ]
527 | ch = int(mult * model_channels)
528 | if ds in attention_resolutions:
529 | layers.append(
530 | AttentionBlock(
531 | ch,
532 | use_checkpoint=use_checkpoint,
533 | num_heads=num_heads,
534 | num_head_channels=num_head_channels,
535 | use_new_attention_order=use_new_attention_order,
536 | )
537 | )
538 | self.input_blocks.append(TimestepEmbedSequential(*layers))
539 | self._feature_size += ch
540 | input_block_chans.append(ch)
541 | if level != len(channel_mult) - 1:
542 | out_ch = ch
543 | self.input_blocks.append(
544 | TimestepEmbedSequential(
545 | ResBlock(
546 | ch,
547 | time_embed_dim,
548 | dropout,
549 | out_channels=out_ch,
550 | dims=dims,
551 | use_checkpoint=use_checkpoint,
552 | use_scale_shift_norm=use_scale_shift_norm,
553 | down=True,
554 | )
555 | if resblock_updown
556 | else Downsample(
557 | ch, conv_resample, dims=dims, out_channels=out_ch
558 | )
559 | )
560 | )
561 | ch = out_ch
562 | input_block_chans.append(ch)
563 | ds *= 2
564 | self._feature_size += ch
565 |
566 | self.middle_block = TimestepEmbedSequential(
567 | ResBlock(
568 | ch,
569 | time_embed_dim,
570 | dropout,
571 | dims=dims,
572 | use_checkpoint=use_checkpoint,
573 | use_scale_shift_norm=use_scale_shift_norm,
574 | ),
575 | AttentionBlock(
576 | ch,
577 | use_checkpoint=use_checkpoint,
578 | num_heads=num_heads,
579 | num_head_channels=num_head_channels,
580 | use_new_attention_order=use_new_attention_order,
581 | ),
582 | ResBlock(
583 | ch,
584 | time_embed_dim,
585 | dropout,
586 | dims=dims,
587 | use_checkpoint=use_checkpoint,
588 | use_scale_shift_norm=use_scale_shift_norm,
589 | ),
590 | )
591 | self._feature_size += ch
592 |
593 | self.output_blocks = nn.ModuleList([])
594 | for level, mult in list(enumerate(channel_mult))[::-1]:
595 | for i in range(num_res_blocks + 1):
596 | ich = input_block_chans.pop()
597 | layers = [
598 | ResBlock(
599 | ch + ich,
600 | time_embed_dim,
601 | dropout,
602 | out_channels=int(model_channels * mult),
603 | dims=dims,
604 | use_checkpoint=use_checkpoint,
605 | use_scale_shift_norm=use_scale_shift_norm,
606 | )
607 | ]
608 | ch = int(model_channels * mult)
609 | if ds in attention_resolutions:
610 | layers.append(
611 | AttentionBlock(
612 | ch,
613 | use_checkpoint=use_checkpoint,
614 | num_heads=num_heads_upsample,
615 | num_head_channels=num_head_channels,
616 | use_new_attention_order=use_new_attention_order,
617 | )
618 | )
619 | if level and i == num_res_blocks:
620 | out_ch = ch
621 | layers.append(
622 | ResBlock(
623 | ch,
624 | time_embed_dim,
625 | dropout,
626 | out_channels=out_ch,
627 | dims=dims,
628 | use_checkpoint=use_checkpoint,
629 | use_scale_shift_norm=use_scale_shift_norm,
630 | up=True,
631 | )
632 | if resblock_updown
633 | else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
634 | )
635 | ds //= 2
636 | self.output_blocks.append(TimestepEmbedSequential(*layers))
637 | self._feature_size += ch
638 |
639 | # Register forward hook to the attention map
640 | if sel_attn_block == "middle":
641 | self.extract_attention = self.middle_block[1].attention
642 | elif sel_attn_block == "output":
643 | assert sel_attn_depth <= 8 and sel_attn_depth >= 0, "sel_attn_depth must be between 0 and 8"
644 | self.extract_attention = self.output_blocks[sel_attn_depth][1].attention
645 | else:
646 | raise ValueError("sel_attn_block must be 'middle' or 'output'")
647 |
648 | self.extract_attention.register_forward_hook(save_input_hook)
649 |
650 | self.out = nn.Sequential(
651 | normalization(ch),
652 | nn.SiLU(),
653 | zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
654 | )
655 |
656 | def convert_to_fp16(self):
657 | """
658 | Convert the torso of the model to float16.
659 | """
660 | self.input_blocks.apply(convert_module_to_f16)
661 | self.middle_block.apply(convert_module_to_f16)
662 | self.output_blocks.apply(convert_module_to_f16)
663 |
664 | def convert_to_fp32(self):
665 | """
666 | Convert the torso of the model to float32.
667 | """
668 | self.input_blocks.apply(convert_module_to_f32)
669 | self.middle_block.apply(convert_module_to_f32)
670 | self.output_blocks.apply(convert_module_to_f32)
671 |
672 | def forward(self, x, timesteps, y=None):
673 | """
674 | Apply the model to an input batch.
675 |
676 | :param x: an [N x C x ...] Tensor of inputs.
677 | :param timesteps: a 1-D batch of timesteps.
678 | :param y: an [N] Tensor of labels, if class-conditional.
679 | :return: an [N x C x ...] Tensor of outputs.
680 | """
681 | assert (y is not None) == (
682 | self.num_classes is not None
683 | ), "must specify y if and only if the model is class-conditional"
684 |
685 | hs = []
686 | emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
687 |
688 | if self.num_classes is not None:
689 | assert y.shape == (x.shape[0],)
690 | emb = emb + self.label_emb(y)
691 |
692 | h = x.type(self.dtype)
693 | for module in self.input_blocks:
694 | h = module(h, emb)
695 | hs.append(h)
696 | h = self.middle_block(h, emb)
697 |
698 | for module in self.output_blocks:
699 | h = th.cat([h, hs.pop()], dim=1)
700 | h = module(h, emb)
701 | h = h.type(x.dtype)
702 |
703 | # Return the attention map with the output
704 | qkv = self.extract_attention.qkv
705 | attention = attention_from_qkv(qkv, self.num_heads)
706 |
707 | return self.out(h), attention
708 |
709 |
710 | class SuperResModel(UNetModel):
711 | """
712 | A UNetModel that performs super-resolution.
713 |
714 | Expects an extra kwarg `low_res` to condition on a low-resolution image.
715 | """
716 |
717 | def __init__(self, image_size, in_channels, *args, **kwargs):
718 | super().__init__(image_size, in_channels * 2, *args, **kwargs)
719 |
720 | def forward(self, x, timesteps, low_res=None, **kwargs):
721 | _, _, new_height, new_width = x.shape
722 | upsampled = F.interpolate(low_res, (new_height, new_width), mode="bilinear")
723 | x = th.cat([x, upsampled], dim=1)
724 | return super().forward(x, timesteps, **kwargs)
725 |
726 |
727 | class EncoderUNetModel(nn.Module):
728 | """
729 | The half UNet model with attention and timestep embedding.
730 |
731 | For usage, see UNet.
732 | """
733 |
734 | def __init__(
735 | self,
736 | image_size,
737 | in_channels,
738 | model_channels,
739 | out_channels,
740 | num_res_blocks,
741 | attention_resolutions,
742 | dropout=0,
743 | channel_mult=(1, 2, 4, 8),
744 | conv_resample=True,
745 | dims=2,
746 | use_checkpoint=False,
747 | use_fp16=False,
748 | num_heads=1,
749 | num_head_channels=-1,
750 | num_heads_upsample=-1,
751 | use_scale_shift_norm=False,
752 | resblock_updown=False,
753 | use_new_attention_order=False,
754 | pool="adaptive",
755 | ):
756 | super().__init__()
757 |
758 | if num_heads_upsample == -1:
759 | num_heads_upsample = num_heads
760 |
761 | self.in_channels = in_channels
762 | self.model_channels = model_channels
763 | self.out_channels = out_channels
764 | self.num_res_blocks = num_res_blocks
765 | self.attention_resolutions = attention_resolutions
766 | self.dropout = dropout
767 | self.channel_mult = channel_mult
768 | self.conv_resample = conv_resample
769 | self.use_checkpoint = use_checkpoint
770 | self.dtype = th.float16 if use_fp16 else th.float32
771 | self.num_heads = num_heads
772 | self.num_head_channels = num_head_channels
773 | self.num_heads_upsample = num_heads_upsample
774 |
775 | time_embed_dim = model_channels * 4
776 | self.time_embed = nn.Sequential(
777 | linear(model_channels, time_embed_dim),
778 | nn.SiLU(),
779 | linear(time_embed_dim, time_embed_dim),
780 | )
781 |
782 | ch = int(channel_mult[0] * model_channels)
783 | self.input_blocks = nn.ModuleList(
784 | [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
785 | )
786 | self._feature_size = ch
787 | input_block_chans = [ch]
788 | ds = 1
789 | for level, mult in enumerate(channel_mult):
790 | for _ in range(num_res_blocks):
791 | layers = [
792 | ResBlock(
793 | ch,
794 | time_embed_dim,
795 | dropout,
796 | out_channels=int(mult * model_channels),
797 | dims=dims,
798 | use_checkpoint=use_checkpoint,
799 | use_scale_shift_norm=use_scale_shift_norm,
800 | )
801 | ]
802 | ch = int(mult * model_channels)
803 | if ds in attention_resolutions:
804 | layers.append(
805 | AttentionBlock(
806 | ch,
807 | use_checkpoint=use_checkpoint,
808 | num_heads=num_heads,
809 | num_head_channels=num_head_channels,
810 | use_new_attention_order=use_new_attention_order,
811 | )
812 | )
813 | self.input_blocks.append(TimestepEmbedSequential(*layers))
814 | self._feature_size += ch
815 | input_block_chans.append(ch)
816 | if level != len(channel_mult) - 1:
817 | out_ch = ch
818 | self.input_blocks.append(
819 | TimestepEmbedSequential(
820 | ResBlock(
821 | ch,
822 | time_embed_dim,
823 | dropout,
824 | out_channels=out_ch,
825 | dims=dims,
826 | use_checkpoint=use_checkpoint,
827 | use_scale_shift_norm=use_scale_shift_norm,
828 | down=True,
829 | )
830 | if resblock_updown
831 | else Downsample(
832 | ch, conv_resample, dims=dims, out_channels=out_ch
833 | )
834 | )
835 | )
836 | ch = out_ch
837 | input_block_chans.append(ch)
838 | ds *= 2
839 | self._feature_size += ch
840 |
841 | self.middle_block = TimestepEmbedSequential(
842 | ResBlock(
843 | ch,
844 | time_embed_dim,
845 | dropout,
846 | dims=dims,
847 | use_checkpoint=use_checkpoint,
848 | use_scale_shift_norm=use_scale_shift_norm,
849 | ),
850 | AttentionBlock(
851 | ch,
852 | use_checkpoint=use_checkpoint,
853 | num_heads=num_heads,
854 | num_head_channels=num_head_channels,
855 | use_new_attention_order=use_new_attention_order,
856 | ),
857 | ResBlock(
858 | ch,
859 | time_embed_dim,
860 | dropout,
861 | dims=dims,
862 | use_checkpoint=use_checkpoint,
863 | use_scale_shift_norm=use_scale_shift_norm,
864 | ),
865 | )
866 | self._feature_size += ch
867 | self.pool = pool
868 | if pool == "adaptive":
869 | self.out = nn.Sequential(
870 | normalization(ch),
871 | nn.SiLU(),
872 | nn.AdaptiveAvgPool2d((1, 1)),
873 | zero_module(conv_nd(dims, ch, out_channels, 1)),
874 | nn.Flatten(),
875 | )
876 | elif pool == "attention":
877 | assert num_head_channels != -1
878 | self.out = nn.Sequential(
879 | normalization(ch),
880 | nn.SiLU(),
881 | AttentionPool2d(
882 | (image_size // ds), ch, num_head_channels, out_channels
883 | ),
884 | )
885 | elif pool == "spatial":
886 | self.out = nn.Sequential(
887 | nn.Linear(self._feature_size, 2048),
888 | nn.ReLU(),
889 | nn.Linear(2048, self.out_channels),
890 | )
891 | elif pool == "spatial_v2":
892 | self.out = nn.Sequential(
893 | nn.Linear(self._feature_size, 2048),
894 | normalization(2048),
895 | nn.SiLU(),
896 | nn.Linear(2048, self.out_channels),
897 | )
898 | else:
899 | raise NotImplementedError(f"Unexpected {pool} pooling")
900 |
901 | def convert_to_fp16(self):
902 | """
903 | Convert the torso of the model to float16.
904 | """
905 | self.input_blocks.apply(convert_module_to_f16)
906 | self.middle_block.apply(convert_module_to_f16)
907 |
908 | def convert_to_fp32(self):
909 | """
910 | Convert the torso of the model to float32.
911 | """
912 | self.input_blocks.apply(convert_module_to_f32)
913 | self.middle_block.apply(convert_module_to_f32)
914 |
915 | def forward(self, x, timesteps):
916 | """
917 | Apply the model to an input batch.
918 |
919 | :param x: an [N x C x ...] Tensor of inputs.
920 | :param timesteps: a 1-D batch of timesteps.
921 | :return: an [N x K] Tensor of outputs.
922 | """
923 | emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
924 |
925 | results = []
926 | h = x.type(self.dtype)
927 | for module in self.input_blocks:
928 | h = module(h, emb)
929 | if self.pool.startswith("spatial"):
930 | results.append(h.type(x.dtype).mean(dim=(2, 3)))
931 | h = self.middle_block(h, emb)
932 | if self.pool.startswith("spatial"):
933 | results.append(h.type(x.dtype).mean(dim=(2, 3)))
934 | h = th.cat(results, axis=-1)
935 | return self.out(h)
936 | else:
937 | h = h.type(x.dtype)
938 | return self.out(h)
939 |
--------------------------------------------------------------------------------
/guided_diffusion/gaussian_diffusion.py:
--------------------------------------------------------------------------------
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 | from math import sqrt
11 |
12 | import numpy as np
13 | import torch as th
14 | import torch.nn.functional as F
15 | import torchvision.transforms as T
16 |
17 | from .losses import discretized_gaussian_log_likelihood, normal_kl
18 | from .nn import mean_flat
19 |
20 |
21 | def get_named_beta_schedule(schedule_name, num_diffusion_timesteps):
22 | """
23 | Get a pre-defined beta schedule for the given name.
24 |
25 | The beta schedule library consists of beta schedules which remain similar
26 | in the limit of num_diffusion_timesteps.
27 | Beta schedules may be added, but should not be removed or changed once
28 | they are committed to maintain backwards compatibility.
29 | """
30 | if schedule_name == "linear":
31 | # Linear schedule from Ho et al, extended to work for any number of
32 | # diffusion steps.
33 | scale = 1000 / num_diffusion_timesteps
34 | beta_start = scale * 0.0001
35 | beta_end = scale * 0.02
36 | return np.linspace(
37 | beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64
38 | )
39 | elif schedule_name == "cosine":
40 | return betas_for_alpha_bar(
41 | num_diffusion_timesteps,
42 | lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
43 | )
44 | else:
45 | raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
46 |
47 |
48 | def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
49 | """
50 | Create a beta schedule that discretizes the given alpha_t_bar function,
51 | which defines the cumulative product of (1-beta) over time from t = [0,1].
52 |
53 | :param num_diffusion_timesteps: the number of betas to produce.
54 | :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
55 | produces the cumulative product of (1-beta) up to that
56 | part of the diffusion process.
57 | :param max_beta: the maximum beta to use; use values lower than 1 to
58 | prevent singularities.
59 | """
60 | betas = []
61 | for i in range(num_diffusion_timesteps):
62 | t1 = i / num_diffusion_timesteps
63 | t2 = (i + 1) / num_diffusion_timesteps
64 | betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
65 | return np.array(betas)
66 |
67 |
68 | class ModelMeanType(enum.Enum):
69 | """
70 | Which type of output the model predicts.
71 | """
72 |
73 | PREVIOUS_X = enum.auto() # the model predicts x_{t-1}
74 | START_X = enum.auto() # the model predicts x_0
75 | EPSILON = enum.auto() # the model predicts epsilon
76 |
77 |
78 | class ModelVarType(enum.Enum):
79 | """
80 | What is used as the model's output variance.
81 |
82 | The LEARNED_RANGE option has been added to allow the model to predict
83 | values between FIXED_SMALL and FIXED_LARGE, making its job easier.
84 | """
85 |
86 | LEARNED = enum.auto()
87 | FIXED_SMALL = enum.auto()
88 | FIXED_LARGE = enum.auto()
89 | LEARNED_RANGE = enum.auto()
90 |
91 |
92 | class LossType(enum.Enum):
93 | MSE = enum.auto() # use raw MSE loss (and KL when learning variances)
94 | RESCALED_MSE = (
95 | enum.auto()
96 | ) # use raw MSE loss (with RESCALED_KL when learning variances)
97 | KL = enum.auto() # use the variational lower-bound
98 | RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB
99 |
100 | def is_vb(self):
101 | return self == LossType.KL or self == LossType.RESCALED_KL
102 |
103 |
104 | class GaussianDiffusion:
105 | """
106 | Utilities for training and sampling diffusion models.
107 |
108 | Ported directly from here, and then adapted over time to further experimentation.
109 | https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42
110 |
111 | :param betas: a 1-D numpy array of betas for each diffusion timestep,
112 | starting at T and going to 1.
113 | :param model_mean_type: a ModelMeanType determining what the model outputs.
114 | :param model_var_type: a ModelVarType determining how variance is output.
115 | :param loss_type: a LossType determining the loss function to use.
116 | :param rescale_timesteps: if True, pass floating point timesteps into the
117 | model so that they are always scaled like in the
118 | original paper (0 to 1000).
119 | """
120 |
121 | def __init__(
122 | self,
123 | *,
124 | betas,
125 | model_mean_type,
126 | model_var_type,
127 | loss_type,
128 | rescale_timesteps=False,
129 | sel_attn_block=None,
130 | sel_attn_depth=None,
131 | num_heads=None,
132 | ):
133 | self.model_mean_type = model_mean_type
134 | self.model_var_type = model_var_type
135 | self.loss_type = loss_type
136 | self.rescale_timesteps = rescale_timesteps
137 | self.sel_attn_block = sel_attn_block
138 | self.sel_attn_depth = sel_attn_depth
139 | self.num_heads = num_heads
140 | # Use float64 for accuracy.
141 | betas = np.array(betas, dtype=np.float64)
142 | self.betas = betas
143 | assert len(betas.shape) == 1, "betas must be 1-D"
144 | assert (betas > 0).all() and (betas <= 1).all()
145 |
146 | self.num_timesteps = int(betas.shape[0])
147 |
148 | alphas = 1.0 - betas
149 | self.sqrt_alphas = np.sqrt(alphas)
150 | self.sqrt_betas = np.sqrt(betas)
151 | self.alphas_cumprod = np.cumprod(alphas, axis=0)
152 | self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1])
153 | self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0)
154 | assert self.alphas_cumprod_prev.shape == (self.num_timesteps,)
155 |
156 | # calculations for diffusion q(x_t | x_{t-1}) and others
157 | self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod)
158 | self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod)
159 | self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod)
160 | self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod)
161 | self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1)
162 |
163 | # calculations for posterior q(x_{t-1} | x_t, x_0)
164 | self.posterior_variance = (
165 | betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
166 | )
167 | # log calculation clipped because the posterior variance is 0 at the
168 | # beginning of the diffusion chain.
169 | self.posterior_log_variance_clipped = np.log(
170 | np.append(self.posterior_variance[1], self.posterior_variance[1:])
171 | )
172 | self.posterior_mean_coef1 = (
173 | betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
174 | )
175 | self.posterior_mean_coef2 = (
176 | (1.0 - self.alphas_cumprod_prev)
177 | * np.sqrt(alphas)
178 | / (1.0 - self.alphas_cumprod)
179 | )
180 |
181 | def q_mean_variance(self, x_start, t):
182 | """
183 | Get the distribution q(x_t | x_0).
184 |
185 | :param x_start: the [N x C x ...] tensor of noiseless inputs.
186 | :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
187 | :return: A tuple (mean, variance, log_variance), all of x_start's shape.
188 | """
189 | mean = (
190 | _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
191 | )
192 | variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
193 | log_variance = _extract_into_tensor(
194 | self.log_one_minus_alphas_cumprod, t, x_start.shape
195 | )
196 | return mean, variance, log_variance
197 |
198 | def q_sample(self, x_start, t, noise=None):
199 | """
200 | Diffuse the data for a given number of diffusion steps.
201 |
202 | In other words, sample from q(x_t | x_0).
203 |
204 | :param x_start: the initial data batch.
205 | :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
206 | :param noise: if specified, the split-out normal noise.
207 | :return: A noisy version of x_start.
208 | """
209 | if noise is None:
210 | noise = th.randn_like(x_start)
211 | assert noise.shape == x_start.shape
212 | return (
213 | _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
214 | + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
215 | * noise
216 | )
217 |
218 | def q_posterior_mean_variance(self, x_start, x_t, t):
219 | """
220 | Compute the mean and variance of the diffusion posterior:
221 |
222 | q(x_{t-1} | x_t, x_0)
223 |
224 | """
225 | assert x_start.shape == x_t.shape
226 | posterior_mean = (
227 | _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start
228 | + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
229 | )
230 | posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape)
231 | posterior_log_variance_clipped = _extract_into_tensor(
232 | self.posterior_log_variance_clipped, t, x_t.shape
233 | )
234 | assert (
235 | posterior_mean.shape[0]
236 | == posterior_variance.shape[0]
237 | == posterior_log_variance_clipped.shape[0]
238 | == x_start.shape[0]
239 | )
240 | return posterior_mean, posterior_variance, posterior_log_variance_clipped
241 |
242 | def p_mean_variance(
243 | self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None
244 | ):
245 | """
246 | Apply the model to get p(x_{t-1} | x_t), as well as a prediction of
247 | the initial x, x_0.
248 |
249 | :param model: the model, which takes a signal and a batch of timesteps
250 | as input.
251 | :param x: the [N x C x ...] tensor at time t.
252 | :param t: a 1-D Tensor of timesteps.
253 | :param clip_denoised: if True, clip the denoised signal into [-1, 1].
254 | :param denoised_fn: if not None, a function which applies to the
255 | x_start prediction before it is used to sample. Applies before
256 | clip_denoised.
257 | :param model_kwargs: if not None, a dict of extra keyword arguments to
258 | pass to the model. This can be used for conditioning.
259 | :return: a dict with the following keys:
260 | - 'mean': the model mean output.
261 | - 'variance': the model variance output.
262 | - 'log_variance': the log of 'variance'.
263 | - 'pred_xstart': the prediction for x_0.
264 | - 'eps': the prediction for eps.
265 | - 'attn_map': the extracted self-attention map.
266 | """
267 | if model_kwargs is None:
268 | model_kwargs = {}
269 |
270 | B, C = x.shape[:2]
271 | assert t.shape == (B,)
272 | model_output, attn_map = model(x, self._scale_timesteps(t), **model_kwargs)
273 |
274 | if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]:
275 | assert model_output.shape == (B, C * 2, *x.shape[2:])
276 | model_output, model_var_values = th.split(model_output, C, dim=1)
277 | if self.model_var_type == ModelVarType.LEARNED:
278 | model_log_variance = model_var_values
279 | model_variance = th.exp(model_log_variance)
280 | else:
281 | min_log = _extract_into_tensor(
282 | self.posterior_log_variance_clipped, t, x.shape
283 | )
284 | max_log = _extract_into_tensor(np.log(self.betas), t, x.shape)
285 | # The model_var_values is [-1, 1] for [min_var, max_var].
286 | frac = (model_var_values + 1) / 2
287 | model_log_variance = frac * max_log + (1 - frac) * min_log
288 | model_variance = th.exp(model_log_variance)
289 | else:
290 | model_variance, model_log_variance = {
291 | # for fixedlarge, we set the initial (log-)variance like so
292 | # to get a better decoder log likelihood.
293 | ModelVarType.FIXED_LARGE: (
294 | np.append(self.posterior_variance[1], self.betas[1:]),
295 | np.log(np.append(self.posterior_variance[1], self.betas[1:])),
296 | ),
297 | ModelVarType.FIXED_SMALL: (
298 | self.posterior_variance,
299 | self.posterior_log_variance_clipped,
300 | ),
301 | }[self.model_var_type]
302 | model_variance = _extract_into_tensor(model_variance, t, x.shape)
303 | model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape)
304 |
305 | def process_xstart(x):
306 | if denoised_fn is not None:
307 | x = denoised_fn(x)
308 | if clip_denoised:
309 | return x.clamp(-1, 1)
310 | return x
311 |
312 | if self.model_mean_type == ModelMeanType.PREVIOUS_X:
313 | pred_xstart = process_xstart(
314 | self._predict_xstart_from_xprev(x_t=x, t=t, xprev=model_output)
315 | )
316 | predicted_epsilon = self._predict_eps_from_xstart(x_t=x, t=t, pred_xstart=pred_xstart)
317 | model_mean = model_output
318 | elif self.model_mean_type in [ModelMeanType.START_X, ModelMeanType.EPSILON]:
319 | if self.model_mean_type == ModelMeanType.START_X:
320 | predicted_epsilon = self._predict_eps_from_xstart(x_t=x, t=t, pred_xstart=model_output)
321 | pred_xstart = process_xstart(model_output)
322 | else:
323 | predicted_epsilon = model_output
324 | pred_xstart = process_xstart(
325 | self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)
326 | )
327 | model_mean, _, _ = self.q_posterior_mean_variance(
328 | x_start=pred_xstart, x_t=x, t=t
329 | )
330 | else:
331 | raise NotImplementedError(self.model_mean_type)
332 |
333 | assert (
334 | model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape
335 | )
336 | return {
337 | "mean": model_mean,
338 | "variance": model_variance,
339 | "log_variance": model_log_variance,
340 | "pred_xstart": pred_xstart,
341 | "eps": predicted_epsilon,
342 | "attn_map": attn_map,
343 | }
344 |
345 | def _predict_xstart_from_eps(self, x_t, t, eps):
346 | assert x_t.shape == eps.shape
347 | return (
348 | _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
349 | - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps
350 | )
351 |
352 | def _predict_xstart_from_xprev(self, x_t, t, xprev):
353 | assert x_t.shape == xprev.shape
354 | return ( # (xprev - coef2*x_t) / coef1
355 | _extract_into_tensor(1.0 / self.posterior_mean_coef1, t, x_t.shape) * xprev
356 | - _extract_into_tensor(
357 | self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape
358 | )
359 | * x_t
360 | )
361 |
362 | def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
363 | return (
364 | _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
365 | - pred_xstart
366 | ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
367 |
368 | def _scale_timesteps(self, t):
369 | if self.rescale_timesteps:
370 | return t.float() * (1000.0 / self.num_timesteps)
371 | return t
372 |
373 | def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
374 | """
375 | Compute the mean for the previous step, given a function cond_fn that
376 | computes the gradient of a conditional log probability with respect to
377 | x. In particular, cond_fn computes grad(log(p(y|x))), and we want to
378 | condition on y.
379 |
380 | This uses the conditioning strategy from Sohl-Dickstein et al. (2015).
381 | """
382 | gradient = cond_fn(x, self._scale_timesteps(t), **model_kwargs)
383 | new_mean = (
384 | p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float()
385 | )
386 | return new_mean
387 |
388 | def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
389 | """
390 | Compute what the p_mean_variance output would have been, should the
391 | model's score function be conditioned by cond_fn.
392 |
393 | See condition_mean() for details on cond_fn.
394 |
395 | Unlike condition_mean(), this instead uses the conditioning strategy
396 | from Song et al (2020).
397 | """
398 | alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
399 |
400 | eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"])
401 | eps = eps - (1 - alpha_bar).sqrt() * cond_fn(
402 | x, self._scale_timesteps(t), **model_kwargs
403 | )
404 |
405 | out = p_mean_var.copy()
406 | out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps)
407 | out["mean"], _, _ = self.q_posterior_mean_variance(
408 | x_start=out["pred_xstart"], x_t=x, t=t
409 | )
410 | return out
411 |
412 | def attention_masking(
413 | self, x, t, attn_map, prev_noise, blur_sigma, model_kwargs=None,
414 | ):
415 | """
416 | Apply the self-attention mask to produce bar{x_t}
417 |
418 | :param x: the predicted x_0 [N x C x ...] tensor at time t.
419 | :param t: a 1-D Tensor of timesteps.
420 | :param attn_map: the attention map tensor at time t.
421 | :param prev_noise: the previously predicted epsilon to inject
422 | the same noise as x_t.
423 | :param blur_sigma: a sigma of Gaussian blur.
424 | :param model_kwargs: if not None, a dict of extra keyword arguments to
425 | pass to the model. This can be used for conditioning.
426 | :return: the bar{x_t}
427 | """
428 | B, C, H, W = x.shape
429 | assert t.shape == (B,)
430 |
431 | if self.sel_attn_depth in [0, 1, 2] or self.sel_attn_block == "middle":
432 | attn_res = 8
433 | elif self.sel_attn_depth in [3, 4, 5]:
434 | attn_res = 16
435 | elif self.sel_attn_depth in [6, 7, 8]:
436 | attn_res = 32
437 | else:
438 | raise ValueError("sel_attn_depth must be in [0, 1, 2, 3, 4, 5, 6, 7, 8]")
439 |
440 | # Generating attention mask
441 | attn_mask = attn_map.reshape(B, self.num_heads, attn_res ** 2, attn_res ** 2).mean(1, keepdim=False).sum(1, keepdim=False) > 1.0
442 | attn_mask = attn_mask.reshape(B, attn_res, attn_res).unsqueeze(1).repeat(1, 3, 1, 1).int().float()
443 | attn_mask = F.interpolate(attn_mask, (H, W))
444 |
445 | # Gaussian blur
446 | transform = T.GaussianBlur(kernel_size=31, sigma=blur_sigma)
447 | x_curr = transform(x)
448 |
449 | # Apply attention masking
450 | x_curr = x_curr * (attn_mask) + x * (1 - attn_mask)
451 |
452 | # Re-inject the noise
453 | x_curr = self.q_sample(x_curr, t, noise=prev_noise)
454 |
455 | return x_curr
456 |
457 | def p_sample(
458 | self,
459 | model,
460 | x,
461 | t,
462 | clip_denoised=True,
463 | denoised_fn=None,
464 | cond_fn=None,
465 | model_kwargs=None,
466 | device=None,
467 | attn_guidance=True,
468 | guidance_kwargs=None,
469 | ):
470 | """
471 | Sample x_{t-1} from the model at the given timestep.
472 |
473 | :param model: the model to sample from.
474 | :param x: the current tensor at x_{t-1}.
475 | :param t: the value of t, starting at 0 for the first diffusion step.
476 | :param clip_denoised: if True, clip the x_start prediction to [-1, 1].
477 | :param denoised_fn: if not None, a function which applies to the
478 | x_start prediction before it is used to sample.
479 | :param cond_fn: if not None, this is a gradient function that acts
480 | similarly to the model.
481 | :param model_kwargs: if not None, a dict of extra keyword arguments to
482 | pass to the model. This can be used for conditioning.
483 | :param attn_guidance: if True, self-attention guidance is given.
484 | :param guidance_kwargs: if not None, a dict of the parameters of self-attention guidance.
485 | :return: a dict containing the following keys:
486 | - 'sample': a random sample from the model.
487 | - 'pred_xstart': a prediction of x_0.
488 | """
489 |
490 | guide_scale = guidance_kwargs['guide_scale']
491 | guide_start = guidance_kwargs['guide_start']
492 | blur_sigma = guidance_kwargs['blur_sigma']
493 |
494 | if attn_guidance and guide_start>t[0]:
495 | out = self.p_mean_variance(
496 | model,
497 | x,
498 | t,
499 | clip_denoised=clip_denoised,
500 | denoised_fn=denoised_fn,
501 | model_kwargs=model_kwargs,
502 | )
503 | # Get the original output: eps(x_t)
504 | cond_eps = out['eps']
505 |
506 | mask_blurred = self.attention_masking(
507 | out['pred_xstart'],
508 | t,
509 | out['attn_map'],
510 | prev_noise=cond_eps,
511 | blur_sigma=blur_sigma,
512 | model_kwargs=model_kwargs,
513 | )
514 | mask_out = self.p_mean_variance(
515 | model,
516 | mask_blurred,
517 | t,
518 | clip_denoised=clip_denoised,
519 | denoised_fn=denoised_fn,
520 | model_kwargs=model_kwargs,
521 | )
522 | # Get the original output: eps(bar{x_t})
523 | uncond_eps = mask_out['eps']
524 |
525 | # Get the guided eps: eps(bar{x_t}) + s * (eps(x_t) - eps(bar{x_t}))
526 | guided_eps = uncond_eps + guide_scale * (cond_eps - uncond_eps)
527 |
528 | def process_xstart(x):
529 | if denoised_fn is not None:
530 | x = denoised_fn(x)
531 | if clip_denoised:
532 | return x.clamp(-1, 1)
533 | return x
534 | pred_xstart = process_xstart(
535 | self._predict_xstart_from_eps(x_t=x, t=t, eps=guided_eps)
536 | )
537 |
538 | final_out = {}
539 | final_out["mean"], _, _ = self.q_posterior_mean_variance(
540 | x_start=pred_xstart, x_t=x, t=t
541 | )
542 | final_out["variance"] = out["variance"]
543 |
544 | noise = th.randn_like(x)
545 | nonzero_mask = (
546 | (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
547 | ) # no noise when t == 0
548 | if cond_fn is not None:
549 | final_out["mean"] = self.condition_mean(
550 | cond_fn, final_out, x, t, model_kwargs=model_kwargs
551 | )
552 |
553 | sample = final_out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise
554 | return {"sample": sample, "pred_xstart": out["pred_xstart"]}
555 |
556 | else: # No self-attention guidance
557 | out = self.p_mean_variance(
558 | model,
559 | x,
560 | t,
561 | clip_denoised=clip_denoised,
562 | denoised_fn=denoised_fn,
563 | model_kwargs=model_kwargs,
564 | )
565 | noise = th.randn_like(x)
566 | nonzero_mask = (
567 | (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
568 | ) # no noise when t == 0
569 | if cond_fn is not None:
570 | out["mean"] = self.condition_mean(
571 | cond_fn, out, x, t, model_kwargs=model_kwargs
572 | )
573 | sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise
574 | return {"sample": sample, "pred_xstart": out["pred_xstart"]}
575 |
576 |
577 | def p_sample_loop(
578 | self,
579 | model,
580 | shape,
581 | noise=None,
582 | clip_denoised=True,
583 | denoised_fn=None,
584 | cond_fn=None,
585 | model_kwargs=None,
586 | device=None,
587 | progress=True,
588 | guidance_kwargs=None
589 | ):
590 | """
591 | Generate samples from the model.
592 |
593 | :param model: the model module.
594 | :param shape: the shape of the samples, (N, C, H, W).
595 | :param noise: if specified, the noise from the encoder to sample.
596 | Should be of the same shape as `shape`.
597 | :param clip_denoised: if True, clip x_start predictions to [-1, 1].
598 | :param denoised_fn: if not None, a function which applies to the
599 | x_start prediction before it is used to sample.
600 | :param cond_fn: if not None, this is a gradient function that acts
601 | similarly to the model.
602 | :param model_kwargs: if not None, a dict of extra keyword arguments to
603 | pass to the model. This can be used for conditioning.
604 | :param device: if specified, the device to create the samples on.
605 | If not specified, use a model parameter's device.
606 | :param progress: if True, show a tqdm progress bar.
607 | :return: a non-differentiable batch of samples.
608 | """
609 | final = None
610 | for sample in self.p_sample_loop_progressive(
611 | model,
612 | shape,
613 | noise=noise,
614 | clip_denoised=clip_denoised,
615 | denoised_fn=denoised_fn,
616 | cond_fn=cond_fn,
617 | model_kwargs=model_kwargs,
618 | device=device,
619 | progress=progress,
620 | guidance_kwargs=guidance_kwargs
621 | ):
622 | final = sample
623 | return final["sample"]
624 |
625 | def p_sample_loop_progressive(
626 | self,
627 | model,
628 | shape,
629 | noise=None,
630 | clip_denoised=True,
631 | denoised_fn=None,
632 | cond_fn=None,
633 | model_kwargs=None,
634 | device=None,
635 | progress=False,
636 | guidance_kwargs=None
637 | ):
638 | """
639 | Generate samples from the model and yield intermediate samples from
640 | each timestep of diffusion.
641 |
642 | Arguments are the same as p_sample_loop().
643 | Returns a generator over dicts, where each dict is the return value of
644 | p_sample().
645 | """
646 | if device is None:
647 | device = next(model.parameters()).device
648 | assert isinstance(shape, (tuple, list))
649 | if noise is not None:
650 | img = noise
651 | else:
652 | img = th.randn(*shape, device=device)
653 | indices = list(range(self.num_timesteps))[::-1]
654 |
655 | if progress:
656 | # Lazy import so that we don't depend on tqdm.
657 | from tqdm.auto import tqdm
658 |
659 | indices = tqdm(indices)
660 |
661 | for i in indices:
662 | t = th.tensor([i] * shape[0], device=device)
663 | with th.no_grad():
664 | out = self.p_sample(
665 | model,
666 | img,
667 | t,
668 | clip_denoised=clip_denoised,
669 | denoised_fn=denoised_fn,
670 | cond_fn=cond_fn,
671 | model_kwargs=model_kwargs,
672 | device=device,
673 | guidance_kwargs=guidance_kwargs
674 | )
675 | yield out
676 | img = out["sample"]
677 |
678 | def ddim_sample(
679 | self,
680 | model,
681 | x,
682 | t,
683 | clip_denoised=True,
684 | denoised_fn=None,
685 | cond_fn=None,
686 | model_kwargs=None,
687 | eta=0.0,
688 | attn_guidance=True,
689 | guidance_kwargs=None,
690 | ):
691 | """
692 | Sample x_{t-1} from the model using DDIM.
693 |
694 | Same usage as p_sample().
695 | """
696 |
697 | guide_scale = guidance_kwargs['guide_scale']
698 | guide_start = guidance_kwargs['guide_start']
699 | blur_sigma = guidance_kwargs['blur_sigma']
700 |
701 | if attn_guidance and guide_start>t[0]:
702 | out = self.p_mean_variance(
703 | model,
704 | x,
705 | t,
706 | clip_denoised=clip_denoised,
707 | denoised_fn=denoised_fn,
708 | model_kwargs=model_kwargs,
709 | )
710 | # Get the original output: eps(x_t)
711 | cond_eps = out["eps"]
712 |
713 | mask_blurred = self.attention_masking(
714 | out['pred_xstart'],
715 | t,
716 | out['attn_map'],
717 | prev_noise=out['eps'],
718 | blur_sigma=blur_sigma,
719 | model_kwargs=model_kwargs,
720 | )
721 | mask_out = self.p_mean_variance(
722 | model,
723 | mask_blurred,
724 | t,
725 | clip_denoised=clip_denoised,
726 | denoised_fn=denoised_fn,
727 | model_kwargs=model_kwargs,
728 | )
729 | # Get the original output: eps(bar{x_t})
730 | uncond_eps = mask_out["eps"]
731 |
732 | # Get the guided eps: eps(bar{x_t}) + s * (eps(x_t) - eps(bar{x_t}))
733 | guided_eps = uncond_eps + guide_scale * (cond_eps - uncond_eps)
734 |
735 | def process_xstart(x):
736 | if denoised_fn is not None:
737 | x = denoised_fn(x)
738 | if clip_denoised:
739 | return x.clamp(-1, 1)
740 | return x
741 |
742 | final_out = {}
743 | final_out["pred_xstart"] = process_xstart(self._predict_xstart_from_eps(x_t=x, t=t, eps=guided_eps))
744 | if cond_fn is not None:
745 | final_out = self.condition_score(cond_fn, final_out, x, t, model_kwargs=model_kwargs)
746 |
747 | # Usually our model outputs epsilon, but we re-derive it
748 | # in case we used x_start or x_prev prediction.
749 | eps = self._predict_eps_from_xstart(x, t, final_out["pred_xstart"])
750 |
751 | alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
752 | alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)
753 | sigma = (
754 | eta
755 | * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
756 | * th.sqrt(1 - alpha_bar / alpha_bar_prev)
757 | )
758 | # Equation 12.
759 | noise = th.randn_like(x)
760 | mean_pred = (
761 | final_out["pred_xstart"] * th.sqrt(alpha_bar_prev)
762 | + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps
763 | )
764 | nonzero_mask = (
765 | (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
766 | ) # no noise when t == 0
767 | sample = mean_pred + nonzero_mask * sigma * noise
768 | return {"sample": sample, "pred_xstart": out["pred_xstart"]}
769 |
770 | else: # No self-attention guidance
771 | out = self.p_mean_variance(
772 | model,
773 | x,
774 | t,
775 | clip_denoised=clip_denoised,
776 | denoised_fn=denoised_fn,
777 | model_kwargs=model_kwargs,
778 | )
779 | if cond_fn is not None:
780 | out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs)
781 |
782 | # Usually our model outputs epsilon, but we re-derive it
783 | # in case we used x_start or x_prev prediction.
784 | eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
785 |
786 | alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
787 | alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)
788 | sigma = (
789 | eta
790 | * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
791 | * th.sqrt(1 - alpha_bar / alpha_bar_prev)
792 | )
793 | # Equation 12.
794 | noise = th.randn_like(x)
795 | mean_pred = (
796 | out["pred_xstart"] * th.sqrt(alpha_bar_prev)
797 | + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps
798 | )
799 | nonzero_mask = (
800 | (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
801 | ) # no noise when t == 0
802 | sample = mean_pred + nonzero_mask * sigma * noise
803 | return {"sample": sample, "pred_xstart": out["pred_xstart"]}
804 |
805 | def ddim_reverse_sample(
806 | self,
807 | model,
808 | x,
809 | t,
810 | clip_denoised=True,
811 | denoised_fn=None,
812 | model_kwargs=None,
813 | eta=0.0,
814 | ):
815 | """
816 | Sample x_{t+1} from the model using DDIM reverse ODE.
817 | """
818 | assert eta == 0.0, "Reverse ODE only for deterministic path"
819 | out = self.p_mean_variance(
820 | model,
821 | x,
822 | t,
823 | clip_denoised=clip_denoised,
824 | denoised_fn=denoised_fn,
825 | model_kwargs=model_kwargs,
826 | )
827 | # Usually our model outputs epsilon, but we re-derive it
828 | # in case we used x_start or x_prev prediction.
829 | eps = (
830 | _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x
831 | - out["pred_xstart"]
832 | ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape)
833 | alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape)
834 |
835 | # Equation 12. reversed
836 | mean_pred = (
837 | out["pred_xstart"] * th.sqrt(alpha_bar_next)
838 | + th.sqrt(1 - alpha_bar_next) * eps
839 | )
840 |
841 | return {"sample": mean_pred, "pred_xstart": out["pred_xstart"]}
842 |
843 | def ddim_sample_loop(
844 | self,
845 | model,
846 | shape,
847 | noise=None,
848 | clip_denoised=True,
849 | denoised_fn=None,
850 | cond_fn=None,
851 | model_kwargs=None,
852 | device=None,
853 | progress=False,
854 | eta=0.0,
855 | guidance_kwargs=None
856 | ):
857 | """
858 | Generate samples from the model using DDIM.
859 |
860 | Same usage as p_sample_loop().
861 | """
862 | final = None
863 | for sample in self.ddim_sample_loop_progressive(
864 | model,
865 | shape,
866 | noise=noise,
867 | clip_denoised=clip_denoised,
868 | denoised_fn=denoised_fn,
869 | cond_fn=cond_fn,
870 | model_kwargs=model_kwargs,
871 | device=device,
872 | progress=progress,
873 | eta=eta,
874 | guidance_kwargs=guidance_kwargs
875 | ):
876 | final = sample
877 | return final["sample"]
878 |
879 | def ddim_sample_loop_progressive(
880 | self,
881 | model,
882 | shape,
883 | noise=None,
884 | clip_denoised=True,
885 | denoised_fn=None,
886 | cond_fn=None,
887 | model_kwargs=None,
888 | device=None,
889 | progress=False,
890 | eta=0.0,
891 | guidance_kwargs=None
892 | ):
893 | """
894 | Use DDIM to sample from the model and yield intermediate samples from
895 | each timestep of DDIM.
896 |
897 | Same usage as p_sample_loop_progressive().
898 | """
899 | if device is None:
900 | device = next(model.parameters()).device
901 | assert isinstance(shape, (tuple, list))
902 | if noise is not None:
903 | img = noise
904 | else:
905 | img = th.randn(*shape, device=device)
906 | indices = list(range(self.num_timesteps))[::-1]
907 |
908 | if progress:
909 | # Lazy import so that we don't depend on tqdm.
910 | from tqdm.auto import tqdm
911 |
912 | indices = tqdm(indices)
913 |
914 | for i in indices:
915 | t = th.tensor([i] * shape[0], device=device)
916 | with th.no_grad():
917 | out = self.ddim_sample(
918 | model,
919 | img,
920 | t,
921 | clip_denoised=clip_denoised,
922 | denoised_fn=denoised_fn,
923 | cond_fn=cond_fn,
924 | model_kwargs=model_kwargs,
925 | eta=eta,
926 | guidance_kwargs=guidance_kwargs
927 | )
928 | yield out
929 | img = out["sample"]
930 |
931 | def _vb_terms_bpd(
932 | self, model, x_start, x_t, t, clip_denoised=True, model_kwargs=None
933 | ):
934 | """
935 | Get a term for the variational lower-bound.
936 |
937 | The resulting units are bits (rather than nats, as one might expect).
938 | This allows for comparison to other papers.
939 |
940 | :return: a dict with the following keys:
941 | - 'output': a shape [N] tensor of NLLs or KLs.
942 | - 'pred_xstart': the x_0 predictions.
943 | """
944 | true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance(
945 | x_start=x_start, x_t=x_t, t=t
946 | )
947 | out = self.p_mean_variance(
948 | model, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs
949 | )
950 | kl = normal_kl(
951 | true_mean, true_log_variance_clipped, out["mean"], out["log_variance"]
952 | )
953 | kl = mean_flat(kl) / np.log(2.0)
954 |
955 | decoder_nll = -discretized_gaussian_log_likelihood(
956 | x_start, means=out["mean"], log_scales=0.5 * out["log_variance"]
957 | )
958 | assert decoder_nll.shape == x_start.shape
959 | decoder_nll = mean_flat(decoder_nll) / np.log(2.0)
960 |
961 | # At the first timestep return the decoder NLL,
962 | # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))
963 | output = th.where((t == 0), decoder_nll, kl)
964 | return {"output": output, "pred_xstart": out["pred_xstart"]}
965 |
966 | def training_losses(self, model, x_start, t, model_kwargs=None, noise=None):
967 | """
968 | Compute training losses for a single timestep.
969 |
970 | :param model: the model to evaluate loss on.
971 | :param x_start: the [N x C x ...] tensor of inputs.
972 | :param t: a batch of timestep indices.
973 | :param model_kwargs: if not None, a dict of extra keyword arguments to
974 | pass to the model. This can be used for conditioning.
975 | :param noise: if specified, the specific Gaussian noise to try to remove.
976 | :return: a dict with the key "loss" containing a tensor of shape [N].
977 | Some mean or variance settings may also have other keys.
978 | """
979 | if model_kwargs is None:
980 | model_kwargs = {}
981 | if noise is None:
982 | noise = th.randn_like(x_start)
983 | x_t = self.q_sample(x_start, t, noise=noise)
984 |
985 | terms = {}
986 |
987 | if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL:
988 | terms["loss"] = self._vb_terms_bpd(
989 | model=model,
990 | x_start=x_start,
991 | x_t=x_t,
992 | t=t,
993 | clip_denoised=False,
994 | model_kwargs=model_kwargs,
995 | )["output"]
996 | if self.loss_type == LossType.RESCALED_KL:
997 | terms["loss"] *= self.num_timesteps
998 | elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE:
999 | model_output = model(x_t, self._scale_timesteps(t), **model_kwargs)
1000 |
1001 | if self.model_var_type in [
1002 | ModelVarType.LEARNED,
1003 | ModelVarType.LEARNED_RANGE,
1004 | ]:
1005 | B, C = x_t.shape[:2]
1006 | assert model_output.shape == (B, C * 2, *x_t.shape[2:])
1007 | model_output, model_var_values = th.split(model_output, C, dim=1)
1008 | # Learn the variance using the variational bound, but don't let
1009 | # it affect our mean prediction.
1010 | frozen_out = th.cat([model_output.detach(), model_var_values], dim=1)
1011 | terms["vb"] = self._vb_terms_bpd(
1012 | model=lambda *args, r=frozen_out: r,
1013 | x_start=x_start,
1014 | x_t=x_t,
1015 | t=t,
1016 | clip_denoised=False,
1017 | )["output"]
1018 | if self.loss_type == LossType.RESCALED_MSE:
1019 | # Divide by 1000 for equivalence with initial implementation.
1020 | # Without a factor of 1/1000, the VB term hurts the MSE term.
1021 | terms["vb"] *= self.num_timesteps / 1000.0
1022 |
1023 | target = {
1024 | ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance(
1025 | x_start=x_start, x_t=x_t, t=t
1026 | )[0],
1027 | ModelMeanType.START_X: x_start,
1028 | ModelMeanType.EPSILON: noise,
1029 | }[self.model_mean_type]
1030 | assert model_output.shape == target.shape == x_start.shape
1031 | terms["mse"] = mean_flat((target - model_output) ** 2)
1032 | if "vb" in terms:
1033 | terms["loss"] = terms["mse"] + terms["vb"]
1034 | else:
1035 | terms["loss"] = terms["mse"]
1036 | else:
1037 | raise NotImplementedError(self.loss_type)
1038 |
1039 | return terms
1040 |
1041 | def _prior_bpd(self, x_start):
1042 | """
1043 | Get the prior KL term for the variational lower-bound, measured in
1044 | bits-per-dim.
1045 |
1046 | This term can't be optimized, as it only depends on the encoder.
1047 |
1048 | :param x_start: the [N x C x ...] tensor of inputs.
1049 | :return: a batch of [N] KL values (in bits), one per batch element.
1050 | """
1051 | batch_size = x_start.shape[0]
1052 | t = th.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
1053 | qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
1054 | kl_prior = normal_kl(
1055 | mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0
1056 | )
1057 | return mean_flat(kl_prior) / np.log(2.0)
1058 |
1059 | def calc_bpd_loop(self, model, x_start, clip_denoised=True, model_kwargs=None):
1060 | """
1061 | Compute the entire variational lower-bound, measured in bits-per-dim,
1062 | as well as other related quantities.
1063 |
1064 | :param model: the model to evaluate loss on.
1065 | :param x_start: the [N x C x ...] tensor of inputs.
1066 | :param clip_denoised: if True, clip denoised samples.
1067 | :param model_kwargs: if not None, a dict of extra keyword arguments to
1068 | pass to the model. This can be used for conditioning.
1069 |
1070 | :return: a dict containing the following keys:
1071 | - total_bpd: the total variational lower-bound, per batch element.
1072 | - prior_bpd: the prior term in the lower-bound.
1073 | - vb: an [N x T] tensor of terms in the lower-bound.
1074 | - xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep.
1075 | - mse: an [N x T] tensor of epsilon MSEs for each timestep.
1076 | """
1077 | device = x_start.device
1078 | batch_size = x_start.shape[0]
1079 |
1080 | vb = []
1081 | xstart_mse = []
1082 | mse = []
1083 | for t in list(range(self.num_timesteps))[::-1]:
1084 | t_batch = th.tensor([t] * batch_size, device=device)
1085 | noise = th.randn_like(x_start)
1086 | x_t = self.q_sample(x_start=x_start, t=t_batch, noise=noise)
1087 | # Calculate VLB term at the current timestep
1088 | with th.no_grad():
1089 | out = self._vb_terms_bpd(
1090 | model,
1091 | x_start=x_start,
1092 | x_t=x_t,
1093 | t=t_batch,
1094 | clip_denoised=clip_denoised,
1095 | model_kwargs=model_kwargs,
1096 | )
1097 | vb.append(out["output"])
1098 | xstart_mse.append(mean_flat((out["pred_xstart"] - x_start) ** 2))
1099 | eps = self._predict_eps_from_xstart(x_t, t_batch, out["pred_xstart"])
1100 | mse.append(mean_flat((eps - noise) ** 2))
1101 |
1102 | vb = th.stack(vb, dim=1)
1103 | xstart_mse = th.stack(xstart_mse, dim=1)
1104 | mse = th.stack(mse, dim=1)
1105 |
1106 | prior_bpd = self._prior_bpd(x_start)
1107 | total_bpd = vb.sum(dim=1) + prior_bpd
1108 | return {
1109 | "total_bpd": total_bpd,
1110 | "prior_bpd": prior_bpd,
1111 | "vb": vb,
1112 | "xstart_mse": xstart_mse,
1113 | "mse": mse,
1114 | }
1115 |
1116 |
1117 | def _extract_into_tensor(arr, timesteps, broadcast_shape):
1118 | """
1119 | Extract values from a 1-D numpy array for a batch of indices.
1120 |
1121 | :param arr: the 1-D numpy array.
1122 | :param timesteps: a tensor of indices into the array to extract.
1123 | :param broadcast_shape: a larger shape of K dimensions with the batch
1124 | dimension equal to the length of timesteps.
1125 | :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims.
1126 | """
1127 | res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float()
1128 | while len(res.shape) < len(broadcast_shape):
1129 | res = res[..., None]
1130 | return res.expand(broadcast_shape)
1131 |
--------------------------------------------------------------------------------