├── LICENSE ├── README.md ├── autoedit.py ├── clip_custom ├── __init__.py ├── bpe_simple_vocab_16e6.txt.gz ├── clip.py ├── model.py └── simple_tokenizer.py ├── datasets ├── README.md └── lsun_bedroom.py ├── encoders ├── modules.py └── x_transformer.py ├── evaluations ├── README.md ├── evaluator.py └── requirements.txt ├── guided_diffusion ├── __init__.py ├── dist_util.py ├── fp16_util.py ├── gaussian_diffusion.py ├── image_datasets.py ├── image_text_datasets.py ├── logger.py ├── losses.py ├── nn.py ├── resample.py ├── respace.py ├── script_util.py ├── train_util.py └── unet.py ├── model-card.md ├── sample.py ├── scripts ├── classifier_sample.py ├── classifier_train.py ├── image_nll.py ├── image_sample.py ├── image_train.py ├── image_train_inpaint.py ├── image_train_latent.py ├── super_res_sample.py └── super_res_train.py └── setup.py /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 OpenAI 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GLID-3-XL 2 | 3 | GLID-3-xl is the [1.4B latent diffusion](https://github.com/CompVis/latent-diffusion#april-2022) model from CompVis back-ported to the guided diffusion codebase 4 | 5 | The model has been split into three checkpoints. This lets us fine tune the diffusion model on new datasets and for additional tasks like inpainting and super-resolution 6 | 7 | # Install 8 | 9 | First install [latent diffusion](https://github.com/CompVis/latent-diffusion) 10 | ``` 11 | # then 12 | git clone https://github.com/Jack000/glid-3-xl 13 | cd glid-3-xl 14 | pip install -e . 15 | ``` 16 | 17 | # Download model files 18 | 19 | ``` 20 | # text encoder (required) 21 | wget https://dall-3.com/models/glid-3-xl/bert.pt 22 | 23 | # ldm first stage (required) 24 | wget https://dall-3.com/models/glid-3-xl/kl-f8.pt 25 | 26 | # there are several diffusion models to choose from: 27 | 28 | # original diffusion model from CompVis 29 | wget https://dall-3.com/models/glid-3-xl/diffusion.pt 30 | 31 | # new model fine tuned on a cleaner dataset (will not generate watermarks, split images or blurry images) 32 | wget https://dall-3.com/models/glid-3-xl/finetune.pt 33 | 34 | # inpaint 35 | wget https://dall-3.com/models/glid-3-xl/inpaint.pt 36 | 37 | ``` 38 | 39 | # Generating images 40 | note: best results at 256x256 image size 41 | 42 | ``` 43 | # fast PLMS sampling 44 | python sample.py --model_path finetune.pt --batch_size 6 --num_batches 6 --text "a cyberpunk girl with a scifi neuralink device on her head" 45 | 46 | # classifier free guidance + CLIP guidance (better adherence to prompt, much slower) 47 | python sample.py --clip_guidance --model_path finetune.pt --batch_size 1 --num_batches 12 --text "a cyberpunk girl with a scifi neuralink device on her head | trending on artstation" 48 | 49 | # sample with an init image 50 | python sample.py --init_image picture.jpg --skip_timesteps 10 --model_path finetune.pt --batch_size 6 --num_batches 6 --text "a cyberpunk girl with a scifi neuralink device on her head" 51 | 52 | # generated images saved to ./output/ 53 | # generated image embeddings saved to ./output_npy/ as npy files 54 | ``` 55 | 56 | 57 | # Editing images 58 | aka human guided diffusion. You can use inpainting to generate more complex prompts by progressively editing the image 59 | 60 | note: you can use > 256px but the model only sees 256x256 at a time, so ensure the inpaint area is smaller than that 61 | 62 | note: inpaint training wip 63 | ``` 64 | 65 | # install PyQt5 if you want to use a gui, otherwise supply a mask file 66 | pip install PyQt5 67 | 68 | # this will pop up a window, use your mouse to paint 69 | # use the generated npy files instead of png for best quality 70 | python sample.py --model_path inpaint.pt --edit output_npy/00000.npy --batch_size 6 --num_batches 6 --text "your prompt" 71 | 72 | # after painting, the mask is saved for re-use 73 | python sample.py --mask mask.png --model_path inpaint.pt --edit output_npy/00000.npy --batch_size 6 --num_batches 6 --text "your prompt" 74 | 75 | # additional arguments for uncropping 76 | python sample.py --edit_x 64 --edit_y 64 --edit_width 128 --edit_height 128 --model_path inpaint.pt --edit output_npy/00000.npy --batch_size 6 --num_batches 6 --text "your prompt" 77 | 78 | # autoedit uses the inpaint model to give the ldm an image prompting function (that works differently from --init_image) 79 | # it continuously edits random parts of the image to maximize clip score for the text prompt 80 | python autoedit.py --edit image.png --model_path inpaint.pt --batch_size 6 --text "your prompt" 81 | 82 | ``` 83 | 84 | # Training/Fine tuning 85 | Train with same flags as guided diffusion. Data directory should contain image and text files with the same name (image1.png image1.txt) 86 | 87 | ``` 88 | # not possible to train on 24gb vram currently! 89 | MODEL_FLAGS="--ema_rate 0.9999 --attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --image_size 32 --learn_sigma False --noise_schedule linear --num_channels 320 --num_heads 8 --num_res_blocks 2 --resblock_updown False --use_fp16 True --use_scale_shift_norm False" 90 | TRAIN_FLAGS="--lr 1e-5 --batch_size 64 --microbatch 1 --log_interval 1 --save_interval 5000 --kl_model kl-f8.pt --bert_model bert.pt --resume_checkpoint diffusion.pt" 91 | export OPENAI_LOGDIR=./logs/ 92 | export TOKENIZERS_PARALLELISM=false 93 | python scripts/image_train_latent.py --data_dir /path/to/data $MODEL_FLAGS $TRAIN_FLAGS 94 | ``` 95 | 96 | Train for inpainting 97 | ``` 98 | # batch size > 1 required 99 | MODEL_FLAGS="--dropout 0.1 --ema_rate 0.9999 --attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --image_size 32 --learn_sigma False --noise_schedule linear --num_channels 320 --num_heads 8 --num_res_blocks 2 --resblock_updown False --use_fp16 True --use_scale_shift_norm False" 100 | TRAIN_FLAGS="--lr --batch_size 64 --microbatch 1 --log_interval 1 --save_interval 5000 --kl_model kl-f8.pt --bert_model bert.pt --resume_checkpoint diffusion.pt" 101 | export OPENAI_LOGDIR=./logs/ 102 | export TOKENIZERS_PARALLELISM=false 103 | python scripts/image_train_inpaint.py --data_dir /path/to/data $MODEL_FLAGS $TRAIN_FLAGS 104 | ``` 105 | -------------------------------------------------------------------------------- /autoedit.py: -------------------------------------------------------------------------------- 1 | import gc 2 | import io 3 | import math 4 | import sys 5 | 6 | from PIL import Image, ImageOps 7 | import requests 8 | import torch 9 | from torch import nn 10 | from torch.nn import functional as F 11 | from torchvision import transforms 12 | from torchvision.transforms import functional as TF 13 | from tqdm.notebook import tqdm 14 | 15 | import numpy as np 16 | 17 | from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults 18 | 19 | from dalle_pytorch import DiscreteVAE, VQGanVAE 20 | 21 | from einops import rearrange 22 | from math import log2, sqrt 23 | 24 | import argparse 25 | import pickle 26 | 27 | import os 28 | 29 | from encoders.modules import BERTEmbedder 30 | 31 | import clip 32 | 33 | # argument parsing 34 | 35 | parser = argparse.ArgumentParser() 36 | 37 | parser.add_argument('--model_path', type=str, default = 'inpaint.pt', 38 | help='path to the diffusion model') 39 | 40 | parser.add_argument('--kl_path', type=str, default = 'kl-f8.pt', 41 | help='path to the LDM first stage model') 42 | 43 | parser.add_argument('--bert_path', type=str, default = 'bert.pt', 44 | help='path to the LDM first stage model') 45 | 46 | parser.add_argument('--text', type = str, required = False, default = '', 47 | help='your text prompt') 48 | 49 | parser.add_argument('--edit', type = str, required = False, 50 | help='path to the image you want to edit (either an image file or .npy containing a numpy array of the image embeddings)') 51 | 52 | parser.add_argument('--mask', type = str, required = False, 53 | help='path to a mask image. white pixels = keep, black pixels = discard. width = image width/8, height = image height/8') 54 | 55 | parser.add_argument('--negative', type = str, required = False, default = '', 56 | help='negative text prompt') 57 | 58 | parser.add_argument('--init_image', type=str, required = False, default = None, 59 | help='init image to use') 60 | 61 | parser.add_argument('--skip_timesteps', type=int, required = False, default = 0, 62 | help='how many diffusion steps are gonna be skipped') 63 | 64 | parser.add_argument('--prefix', type = str, required = False, default = '', 65 | help='prefix for output files') 66 | 67 | parser.add_argument('--num_batches', type = int, default = 1, required = False, 68 | help='number of batches') 69 | 70 | parser.add_argument('--batch_size', type = int, default = 1, required = False, 71 | help='batch size') 72 | 73 | parser.add_argument('--width', type = int, default = 256, required = False, 74 | help='image size of output (multiple of 8)') 75 | 76 | parser.add_argument('--height', type = int, default = 256, required = False, 77 | help='image size of output (multiple of 8)') 78 | 79 | parser.add_argument('--iterations', type = int, default=25, required = False, 80 | help='number of mutation steps') 81 | 82 | parser.add_argument('--starting_threshold', type = float, default=0.6, required = False, 83 | help='how much of the image to replace at the start of editing (1 = inpaint the entire image)') 84 | 85 | parser.add_argument('--ending_threshold', type = float, default=0.5, required = False, 86 | help='how much of the image to replace at the end of editing') 87 | 88 | parser.add_argument('--starting_radius', type = float, default=5, required = False, 89 | help='size of noise blur at the start of editing (larger = coarser changes)') 90 | 91 | parser.add_argument('--ending_radius', type = float, default=0.1, required = False, 92 | help='size of noise blur at the end of editing (smaller = editing fine details)') 93 | 94 | parser.add_argument('--seed', type = int, default=-1, required = False, 95 | help='random seed') 96 | 97 | parser.add_argument('--guidance_scale', type = float, default = 5.0, required = False, 98 | help='classifier-free guidance scale') 99 | 100 | parser.add_argument('--steps', type = int, default = 0, required = False, 101 | help='number of diffusion steps') 102 | 103 | parser.add_argument('--cpu', dest='cpu', action='store_true') 104 | 105 | parser.add_argument('--clip_score', dest='clip_score', action='store_true') 106 | 107 | parser.add_argument('--clip_guidance', dest='clip_guidance', action='store_true') 108 | 109 | parser.add_argument('--clip_guidance_scale', type = float, default = 150, required = False, 110 | help='Controls how much the image should look like the prompt') # may need to use lower value for ddim 111 | 112 | parser.add_argument('--cutn', type = int, default = 16, required = False, 113 | help='Number of cuts') 114 | 115 | parser.add_argument('--ddim', dest='ddim', action='store_true') # turn on to use 50 step ddim 116 | 117 | parser.add_argument('--ddpm', dest='ddpm', action='store_true') # turn on to use 50 step ddim 118 | 119 | args = parser.parse_args() 120 | 121 | def fetch(url_or_path): 122 | if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'): 123 | r = requests.get(url_or_path) 124 | r.raise_for_status() 125 | fd = io.BytesIO() 126 | fd.write(r.content) 127 | fd.seek(0) 128 | return fd 129 | return open(url_or_path, 'rb') 130 | 131 | 132 | class MakeCutouts(nn.Module): 133 | def __init__(self, cut_size, cutn, cut_pow=1.): 134 | super().__init__() 135 | 136 | self.cut_size = cut_size 137 | self.cutn = cutn 138 | self.cut_pow = cut_pow 139 | 140 | def forward(self, input): 141 | sideY, sideX = input.shape[2:4] 142 | max_size = min(sideX, sideY) 143 | min_size = min(sideX, sideY, self.cut_size) 144 | cutouts = [] 145 | for _ in range(self.cutn): 146 | size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size) 147 | offsetx = torch.randint(0, sideX - size + 1, ()) 148 | offsety = torch.randint(0, sideY - size + 1, ()) 149 | cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size] 150 | cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size)) 151 | return torch.cat(cutouts) 152 | 153 | 154 | def spherical_dist_loss(x, y): 155 | x = F.normalize(x, dim=-1) 156 | y = F.normalize(y, dim=-1) 157 | return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2) 158 | 159 | 160 | def tv_loss(input): 161 | """L2 total variation loss, as in Mahendran et al.""" 162 | input = F.pad(input, (0, 1, 0, 1), 'replicate') 163 | x_diff = input[..., :-1, 1:] - input[..., :-1, :-1] 164 | y_diff = input[..., 1:, :-1] - input[..., :-1, :-1] 165 | return (x_diff**2 + y_diff**2).mean([1, 2, 3]) 166 | 167 | device = torch.device('cuda:0' if (torch.cuda.is_available() and not args.cpu) else 'cpu') 168 | print('Using device:', device) 169 | 170 | model_state_dict = torch.load(args.model_path, map_location='cpu') 171 | 172 | model_params = { 173 | 'attention_resolutions': '32,16,8', 174 | 'class_cond': False, 175 | 'diffusion_steps': 1000, 176 | 'rescale_timesteps': True, 177 | 'timestep_respacing': '27', # Modify this value to decrease the number of 178 | # timesteps. 179 | 'image_size': 32, 180 | 'learn_sigma': False, 181 | 'noise_schedule': 'linear', 182 | 'num_channels': 320, 183 | 'num_heads': 8, 184 | 'num_res_blocks': 2, 185 | 'resblock_updown': False, 186 | 'use_fp16': False, 187 | 'use_scale_shift_norm': False, 188 | 'clip_embed_dim': 768 if 'clip_proj.weight' in model_state_dict else None, 189 | 'image_condition': True if model_state_dict['input_blocks.0.0.weight'].shape[1] == 8 else False, 190 | 'super_res_condition': True if 'external_block.0.0.weight' in model_state_dict else False, 191 | } 192 | 193 | if args.ddpm: 194 | model_params['timestep_respacing'] = 1000 195 | if args.ddim: 196 | if args.steps: 197 | model_params['timestep_respacing'] = 'ddim'+str(args.steps) 198 | else: 199 | model_params['timestep_respacing'] = 'ddim50' 200 | elif args.steps: 201 | model_params['timestep_respacing'] = str(args.steps) 202 | 203 | model_config = model_and_diffusion_defaults() 204 | model_config.update(model_params) 205 | 206 | if args.cpu: 207 | model_config['use_fp16'] = False 208 | 209 | # Load models 210 | model, diffusion = create_model_and_diffusion(**model_config) 211 | model.load_state_dict(model_state_dict, strict=False) 212 | model.requires_grad_(args.clip_guidance).eval().to(device) 213 | 214 | if model_config['use_fp16']: 215 | model.convert_to_fp16() 216 | else: 217 | model.convert_to_fp32() 218 | 219 | def set_requires_grad(model, value): 220 | for param in model.parameters(): 221 | param.requires_grad = value 222 | 223 | # vae 224 | ldm = torch.load(args.kl_path, map_location="cpu") 225 | ldm.to(device) 226 | ldm.eval() 227 | ldm.requires_grad_(args.clip_guidance) 228 | set_requires_grad(ldm, args.clip_guidance) 229 | 230 | bert = BERTEmbedder(1280, 32) 231 | sd = torch.load(args.bert_path, map_location="cpu") 232 | bert.load_state_dict(sd) 233 | 234 | bert.to(device) 235 | bert.half().eval() 236 | set_requires_grad(bert, False) 237 | 238 | # clip 239 | clip_model, clip_preprocess = clip.load('ViT-L/14', device=device, jit=False) 240 | clip_model.eval().requires_grad_(False) 241 | normalize = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]) 242 | 243 | # bert context 244 | text_emb = bert.encode([args.text]*args.batch_size).to(device).float() 245 | text_blank = bert.encode([args.negative]*args.batch_size).to(device).float() 246 | 247 | text = clip.tokenize([args.text]*args.batch_size, truncate=True).to(device) 248 | text_clip_blank = clip.tokenize([args.negative]*args.batch_size, truncate=True).to(device) 249 | 250 | # clip context 251 | text_emb_clip = clip_model.encode_text(text) 252 | text_emb_clip_blank = clip_model.encode_text(text_clip_blank) 253 | text_emb_norm = text_emb_clip[0] / text_emb_clip[0].norm(dim=-1, keepdim=True) 254 | 255 | if args.seed >= 0: 256 | torch.manual_seed(args.seed) 257 | 258 | image_embed = None 259 | 260 | # image context 261 | if args.edit: 262 | if args.edit.endswith('.npy'): 263 | with open(args.edit, 'rb') as f: 264 | input_image = np.load(f) 265 | input_image = torch.from_numpy(input_image).unsqueeze(0).to(device) 266 | 267 | input_image_pil = ldm.decode(input_image) 268 | input_image_pil = TF.to_pil_image(input_image_pil.squeeze(0).add(1).div(2).clamp(0, 1)) 269 | 270 | input_image *= 0.18215 271 | else: 272 | input_image_pil = Image.open(fetch(args.edit)).convert('RGB') 273 | input_image_pil = ImageOps.fit(input_image_pil, (args.width, args.height)) 274 | 275 | input_image = transforms.ToTensor()(input_image_pil).unsqueeze(0).to(device) 276 | input_image = 2*input_image-1 277 | input_image = 0.18215*ldm.encode(input_image).sample() 278 | 279 | image_embed = torch.cat(args.batch_size*2*[input_image], dim=0).float() 280 | elif model_params['image_condition']: 281 | # using inpaint model but no image is provided 282 | image_embed = torch.zeros(args.batch_size*2, 4, args.height//8, args.width//8, device=device) 283 | 284 | # Create a classifier-free guidance sampling function 285 | def model_fn(x_t, ts, **kwargs): 286 | half = x_t[: len(x_t) // 2] 287 | combined = torch.cat([half, half], dim=0) 288 | model_out = model(combined, ts, **kwargs) 289 | eps, rest = model_out[:, :3], model_out[:, 3:] 290 | cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) 291 | half_eps = uncond_eps + args.guidance_scale * (cond_eps - uncond_eps) 292 | eps = torch.cat([half_eps, half_eps], dim=0) 293 | return torch.cat([eps, rest], dim=1) 294 | 295 | 296 | def save_sample(i, sample, clip_score=False): 297 | for k, image in enumerate(sample['pred_xstart'][:args.batch_size]): 298 | image /= 0.18215 299 | im = image.unsqueeze(0) 300 | out = ldm.decode(im) 301 | 302 | npy_filename = f'output_npy/{args.prefix}{i * args.batch_size + k:05}.npy' 303 | with open(npy_filename, 'wb') as outfile: 304 | np.save(outfile, image.detach().cpu().numpy()) 305 | 306 | out = TF.to_pil_image(out.squeeze(0).add(1).div(2).clamp(0, 1)) 307 | 308 | filename = f'output/{args.prefix}{i * args.batch_size + k:05}.png' 309 | out.save(filename) 310 | 311 | if clip_score: 312 | image_emb = clip_model.encode_image(clip_preprocess(out).unsqueeze(0).to(device)) 313 | image_emb_norm = image_emb / image_emb.norm(dim=-1, keepdim=True) 314 | 315 | similarity = torch.nn.functional.cosine_similarity(image_emb_norm, text_emb_norm, dim=-1) 316 | 317 | final_filename = f'output/{args.prefix}_{similarity.item():0.3f}_{i * args.batch_size + k:05}.png' 318 | os.rename(filename, final_filename) 319 | 320 | npy_final = f'output_npy/{args.prefix}_{similarity.item():0.3f}_{i * args.batch_size + k:05}.npy' 321 | os.rename(npy_filename, npy_final) 322 | 323 | def save_image(i, image): 324 | image /= 0.18215 325 | im = image.unsqueeze(0) 326 | out = ldm.decode(im) 327 | npy_filename = f'output_npy/{args.prefix}{i:05}.npy' 328 | with open(npy_filename, 'wb') as outfile: 329 | np.save(outfile, image.detach().cpu().numpy()) 330 | 331 | out = TF.to_pil_image(out.squeeze(0).add(1).div(2).clamp(0, 1)) 332 | 333 | filename = f'output/{args.prefix}{i:05}.png' 334 | out.save(filename) 335 | 336 | population = [] 337 | population_scores = [] 338 | 339 | for i in range(args.iterations): 340 | 341 | print('iteration ', i) 342 | 343 | kwargs = { 344 | "context": torch.cat([text_emb, text_blank], dim=0).float(), 345 | "clip_embed": torch.cat([text_emb_clip, text_emb_clip_blank], dim=0).float() if model_params['clip_embed_dim'] else None, 346 | "image_embed": image_embed 347 | } 348 | 349 | if args.ddpm: 350 | sample_fn = diffusion.ddpm_sample_loop_progressive 351 | elif args.ddim: 352 | sample_fn = diffusion.ddim_sample_loop_progressive 353 | else: 354 | sample_fn = diffusion.plms_sample_loop_progressive 355 | 356 | samples = sample_fn( 357 | model_fn, 358 | (args.batch_size*2, 4, int(args.height/8), int(args.width/8)), 359 | clip_denoised=False, 360 | model_kwargs=kwargs, 361 | cond_fn=None, 362 | device=device, 363 | progress=True, 364 | init_image=None, 365 | skip_timesteps=0, 366 | ) 367 | 368 | for j, sample in enumerate(samples): 369 | pass 370 | 371 | for k, image in enumerate(sample['pred_xstart'][:args.batch_size]): 372 | im = image/0.18215 373 | im = im.unsqueeze(0) 374 | out = ldm.decode(im) 375 | 376 | out = TF.to_pil_image(out.squeeze(0).add(1).div(2).clamp(0, 1)) 377 | 378 | image_emb = clip_model.encode_image(clip_preprocess(out).unsqueeze(0).to(device)) 379 | image_emb_norm = image_emb / image_emb.norm(dim=-1, keepdim=True) 380 | 381 | similarity = torch.nn.functional.cosine_similarity(image_emb_norm, text_emb_norm, dim=-1) 382 | 383 | if i == 0: 384 | population.append(image.unsqueeze(0)) 385 | population_scores.append(similarity) 386 | save_image(k, image.detach().clone()) 387 | elif similarity > population_scores[k]: 388 | population[k] = image.unsqueeze(0) 389 | population_scores[k] = similarity 390 | save_image(k, image.detach().clone()) 391 | print(k, similarity.item()) 392 | 393 | image_embed = torch.cat(population+population, dim=0) 394 | 395 | radius = (args.starting_radius-args.ending_radius)*(1 - (i/args.iterations)) + args.ending_radius 396 | 397 | blur = transforms.GaussianBlur(kernel_size=(15, 15), sigma=radius) 398 | mask = torch.randn(args.batch_size, 1, args.height//8, args.width//8) 399 | mask = blur(mask) 400 | 401 | q = (args.starting_threshold-args.ending_threshold)*(1 - (i/args.iterations)) + args.ending_threshold 402 | threshold = torch.quantile(mask, q) 403 | mask = (mask > threshold).float() 404 | 405 | #im_mask = TF.to_pil_image(mask[0]) 406 | #im_mask.save('mask_recur.png') 407 | 408 | 409 | mask = mask.repeat(1, 4, 1, 1).to(device) 410 | 411 | mask = torch.cat([mask,mask], dim=0) 412 | 413 | image_embed *= mask 414 | -------------------------------------------------------------------------------- /clip_custom/__init__.py: -------------------------------------------------------------------------------- 1 | from .clip import * 2 | -------------------------------------------------------------------------------- /clip_custom/bpe_simple_vocab_16e6.txt.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jack000/glid-3-xl/a0b5be4b04378d4d4779240d3e0a599360c1a133/clip_custom/bpe_simple_vocab_16e6.txt.gz -------------------------------------------------------------------------------- /clip_custom/clip.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import os 3 | import urllib 4 | import warnings 5 | from typing import Any, Union, List 6 | from pkg_resources import packaging 7 | 8 | import torch 9 | from PIL import Image 10 | from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize 11 | from tqdm import tqdm 12 | 13 | from .model import build_model 14 | from .simple_tokenizer import SimpleTokenizer as _Tokenizer 15 | 16 | try: 17 | from torchvision.transforms import InterpolationMode 18 | BICUBIC = InterpolationMode.BICUBIC 19 | except ImportError: 20 | BICUBIC = Image.BICUBIC 21 | 22 | 23 | if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"): 24 | warnings.warn("PyTorch version 1.7.1 or higher is recommended") 25 | 26 | 27 | __all__ = ["available_models", "load", "tokenize"] 28 | _tokenizer = _Tokenizer() 29 | 30 | _MODELS = { 31 | "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt", 32 | "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt", 33 | "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt", 34 | "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt", 35 | "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt", 36 | "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt", 37 | "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt", 38 | "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt", 39 | } 40 | 41 | 42 | def _download(url: str, root: str): 43 | os.makedirs(root, exist_ok=True) 44 | filename = os.path.basename(url) 45 | 46 | expected_sha256 = url.split("/")[-2] 47 | download_target = os.path.join(root, filename) 48 | 49 | if os.path.exists(download_target) and not os.path.isfile(download_target): 50 | raise RuntimeError(f"{download_target} exists and is not a regular file") 51 | 52 | if os.path.isfile(download_target): 53 | if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256: 54 | return download_target 55 | else: 56 | warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") 57 | 58 | with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: 59 | with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop: 60 | while True: 61 | buffer = source.read(8192) 62 | if not buffer: 63 | break 64 | 65 | output.write(buffer) 66 | loop.update(len(buffer)) 67 | 68 | if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256: 69 | raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match") 70 | 71 | return download_target 72 | 73 | 74 | def _convert_image_to_rgb(image): 75 | return image.convert("RGB") 76 | 77 | 78 | def _transform(n_px): 79 | return Compose([ 80 | Resize(n_px, interpolation=BICUBIC), 81 | CenterCrop(n_px), 82 | _convert_image_to_rgb, 83 | ToTensor(), 84 | Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), 85 | ]) 86 | 87 | 88 | def available_models() -> List[str]: 89 | """Returns the names of available CLIP models""" 90 | return list(_MODELS.keys()) 91 | 92 | 93 | def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None): 94 | """Load a CLIP model 95 | 96 | Parameters 97 | ---------- 98 | name : str 99 | A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict 100 | 101 | device : Union[str, torch.device] 102 | The device to put the loaded model 103 | 104 | jit : bool 105 | Whether to load the optimized JIT model or more hackable non-JIT model (default). 106 | 107 | download_root: str 108 | path to download the model files; by default, it uses "~/.cache/clip" 109 | 110 | Returns 111 | ------- 112 | model : torch.nn.Module 113 | The CLIP model 114 | 115 | preprocess : Callable[[PIL.Image], torch.Tensor] 116 | A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input 117 | """ 118 | if name in _MODELS: 119 | model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip")) 120 | elif os.path.isfile(name): 121 | model_path = name 122 | else: 123 | raise RuntimeError(f"Model {name} not found; available models = {available_models()}") 124 | 125 | try: 126 | # loading JIT archive 127 | model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval() 128 | state_dict = None 129 | except RuntimeError: 130 | # loading saved state dict 131 | if jit: 132 | warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead") 133 | jit = False 134 | state_dict = torch.load(model_path, map_location="cpu") 135 | 136 | if not jit: 137 | model = build_model(state_dict or model.state_dict()).to(device) 138 | if str(device) == "cpu": 139 | model.float() 140 | return model, _transform(model.visual.input_resolution) 141 | 142 | # patch the device names 143 | device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[]) 144 | device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1] 145 | 146 | def patch_device(module): 147 | try: 148 | graphs = [module.graph] if hasattr(module, "graph") else [] 149 | except RuntimeError: 150 | graphs = [] 151 | 152 | if hasattr(module, "forward1"): 153 | graphs.append(module.forward1.graph) 154 | 155 | for graph in graphs: 156 | for node in graph.findAllNodes("prim::Constant"): 157 | if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"): 158 | node.copyAttributes(device_node) 159 | 160 | model.apply(patch_device) 161 | patch_device(model.encode_image) 162 | patch_device(model.encode_text) 163 | 164 | # patch dtype to float32 on CPU 165 | if str(device) == "cpu": 166 | float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[]) 167 | float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] 168 | float_node = float_input.node() 169 | 170 | def patch_float(module): 171 | try: 172 | graphs = [module.graph] if hasattr(module, "graph") else [] 173 | except RuntimeError: 174 | graphs = [] 175 | 176 | if hasattr(module, "forward1"): 177 | graphs.append(module.forward1.graph) 178 | 179 | for graph in graphs: 180 | for node in graph.findAllNodes("aten::to"): 181 | inputs = list(node.inputs()) 182 | for i in [1, 2]: # dtype can be the second or third argument to aten::to() 183 | if inputs[i].node()["value"] == 5: 184 | inputs[i].node().copyAttributes(float_node) 185 | 186 | model.apply(patch_float) 187 | patch_float(model.encode_image) 188 | patch_float(model.encode_text) 189 | 190 | model.float() 191 | 192 | return model, _transform(model.input_resolution.item()) 193 | 194 | 195 | def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> torch.LongTensor: 196 | """ 197 | Returns the tokenized representation of given input string(s) 198 | 199 | Parameters 200 | ---------- 201 | texts : Union[str, List[str]] 202 | An input string or a list of input strings to tokenize 203 | 204 | context_length : int 205 | The context length to use; all CLIP models use 77 as the context length 206 | 207 | truncate: bool 208 | Whether to truncate the text in case its encoding is longer than the context length 209 | 210 | Returns 211 | ------- 212 | A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] 213 | """ 214 | if isinstance(texts, str): 215 | texts = [texts] 216 | 217 | sot_token = _tokenizer.encoder["<|startoftext|>"] 218 | eot_token = _tokenizer.encoder["<|endoftext|>"] 219 | all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] 220 | result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) 221 | 222 | for i, tokens in enumerate(all_tokens): 223 | if len(tokens) > context_length: 224 | if truncate: 225 | tokens = tokens[:context_length] 226 | tokens[-1] = eot_token 227 | else: 228 | raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") 229 | result[i, :len(tokens)] = torch.tensor(tokens) 230 | 231 | return result 232 | -------------------------------------------------------------------------------- /clip_custom/model.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | from typing import Tuple, Union 3 | 4 | import numpy as np 5 | import torch 6 | import torch.nn.functional as F 7 | from torch import nn 8 | 9 | 10 | class Bottleneck(nn.Module): 11 | expansion = 4 12 | 13 | def __init__(self, inplanes, planes, stride=1): 14 | super().__init__() 15 | 16 | # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 17 | self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) 18 | self.bn1 = nn.BatchNorm2d(planes) 19 | 20 | self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) 21 | self.bn2 = nn.BatchNorm2d(planes) 22 | 23 | self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() 24 | 25 | self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) 26 | self.bn3 = nn.BatchNorm2d(planes * self.expansion) 27 | 28 | self.relu = nn.ReLU(inplace=True) 29 | self.downsample = None 30 | self.stride = stride 31 | 32 | if stride > 1 or inplanes != planes * Bottleneck.expansion: 33 | # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 34 | self.downsample = nn.Sequential(OrderedDict([ 35 | ("-1", nn.AvgPool2d(stride)), 36 | ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), 37 | ("1", nn.BatchNorm2d(planes * self.expansion)) 38 | ])) 39 | 40 | def forward(self, x: torch.Tensor): 41 | identity = x 42 | 43 | out = self.relu(self.bn1(self.conv1(x))) 44 | out = self.relu(self.bn2(self.conv2(out))) 45 | out = self.avgpool(out) 46 | out = self.bn3(self.conv3(out)) 47 | 48 | if self.downsample is not None: 49 | identity = self.downsample(x) 50 | 51 | out += identity 52 | out = self.relu(out) 53 | return out 54 | 55 | 56 | class AttentionPool2d(nn.Module): 57 | def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): 58 | super().__init__() 59 | self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) 60 | self.k_proj = nn.Linear(embed_dim, embed_dim) 61 | self.q_proj = nn.Linear(embed_dim, embed_dim) 62 | self.v_proj = nn.Linear(embed_dim, embed_dim) 63 | self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) 64 | self.num_heads = num_heads 65 | 66 | def forward(self, x): 67 | x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC 68 | x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC 69 | x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC 70 | x, _ = F.multi_head_attention_forward( 71 | query=x, key=x, value=x, 72 | embed_dim_to_check=x.shape[-1], 73 | num_heads=self.num_heads, 74 | q_proj_weight=self.q_proj.weight, 75 | k_proj_weight=self.k_proj.weight, 76 | v_proj_weight=self.v_proj.weight, 77 | in_proj_weight=None, 78 | in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), 79 | bias_k=None, 80 | bias_v=None, 81 | add_zero_attn=False, 82 | dropout_p=0, 83 | out_proj_weight=self.c_proj.weight, 84 | out_proj_bias=self.c_proj.bias, 85 | use_separate_proj_weight=True, 86 | training=self.training, 87 | need_weights=False 88 | ) 89 | 90 | return x[0] 91 | 92 | 93 | class ModifiedResNet(nn.Module): 94 | """ 95 | A ResNet class that is similar to torchvision's but contains the following changes: 96 | - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. 97 | - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 98 | - The final pooling layer is a QKV attention instead of an average pool 99 | """ 100 | 101 | def __init__(self, layers, output_dim, heads, input_resolution=224, width=64): 102 | super().__init__() 103 | self.output_dim = output_dim 104 | self.input_resolution = input_resolution 105 | 106 | # the 3-layer stem 107 | self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False) 108 | self.bn1 = nn.BatchNorm2d(width // 2) 109 | self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False) 110 | self.bn2 = nn.BatchNorm2d(width // 2) 111 | self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False) 112 | self.bn3 = nn.BatchNorm2d(width) 113 | self.avgpool = nn.AvgPool2d(2) 114 | self.relu = nn.ReLU(inplace=True) 115 | 116 | # residual layers 117 | self._inplanes = width # this is a *mutable* variable used during construction 118 | self.layer1 = self._make_layer(width, layers[0]) 119 | self.layer2 = self._make_layer(width * 2, layers[1], stride=2) 120 | self.layer3 = self._make_layer(width * 4, layers[2], stride=2) 121 | self.layer4 = self._make_layer(width * 8, layers[3], stride=2) 122 | 123 | embed_dim = width * 32 # the ResNet feature dimension 124 | self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim) 125 | 126 | def _make_layer(self, planes, blocks, stride=1): 127 | layers = [Bottleneck(self._inplanes, planes, stride)] 128 | 129 | self._inplanes = planes * Bottleneck.expansion 130 | for _ in range(1, blocks): 131 | layers.append(Bottleneck(self._inplanes, planes)) 132 | 133 | return nn.Sequential(*layers) 134 | 135 | def forward(self, x): 136 | def stem(x): 137 | for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]: 138 | x = self.relu(bn(conv(x))) 139 | x = self.avgpool(x) 140 | return x 141 | 142 | x = x.type(self.conv1.weight.dtype) 143 | x = stem(x) 144 | x = self.layer1(x) 145 | x = self.layer2(x) 146 | x = self.layer3(x) 147 | x = self.layer4(x) 148 | x = self.attnpool(x) 149 | 150 | return x 151 | 152 | 153 | class LayerNorm(nn.LayerNorm): 154 | """Subclass torch's LayerNorm to handle fp16.""" 155 | 156 | def forward(self, x: torch.Tensor): 157 | orig_type = x.dtype 158 | ret = super().forward(x.type(torch.float32)) 159 | return ret.type(orig_type) 160 | 161 | 162 | class QuickGELU(nn.Module): 163 | def forward(self, x: torch.Tensor): 164 | return x * torch.sigmoid(1.702 * x) 165 | 166 | 167 | class ResidualAttentionBlock(nn.Module): 168 | def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): 169 | super().__init__() 170 | 171 | self.attn = nn.MultiheadAttention(d_model, n_head) 172 | self.ln_1 = LayerNorm(d_model) 173 | self.mlp = nn.Sequential(OrderedDict([ 174 | ("c_fc", nn.Linear(d_model, d_model * 4)), 175 | ("gelu", QuickGELU()), 176 | ("c_proj", nn.Linear(d_model * 4, d_model)) 177 | ])) 178 | self.ln_2 = LayerNorm(d_model) 179 | self.attn_mask = attn_mask 180 | 181 | def attention(self, x: torch.Tensor): 182 | self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None 183 | return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] 184 | 185 | def forward(self, x: torch.Tensor): 186 | x = x + self.attention(self.ln_1(x)) 187 | x = x + self.mlp(self.ln_2(x)) 188 | return x 189 | 190 | 191 | class Transformer(nn.Module): 192 | def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None): 193 | super().__init__() 194 | self.width = width 195 | self.layers = layers 196 | self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) 197 | 198 | def forward(self, x: torch.Tensor): 199 | return self.resblocks(x) 200 | 201 | 202 | class VisionTransformer(nn.Module): 203 | def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int): 204 | super().__init__() 205 | self.input_resolution = input_resolution 206 | self.output_dim = output_dim 207 | self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) 208 | 209 | scale = width ** -0.5 210 | self.class_embedding = nn.Parameter(scale * torch.randn(width)) 211 | self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) 212 | self.ln_pre = LayerNorm(width) 213 | 214 | self.transformer = Transformer(width, layers, heads) 215 | 216 | self.ln_post = LayerNorm(width) 217 | self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) 218 | 219 | def forward(self, x: torch.Tensor): 220 | x = self.conv1(x) # shape = [*, width, grid, grid] 221 | x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] 222 | x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] 223 | x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width] 224 | x = x + self.positional_embedding.to(x.dtype) 225 | x = self.ln_pre(x) 226 | 227 | x = x.permute(1, 0, 2) # NLD -> LND 228 | x = self.transformer(x) 229 | x = x.permute(1, 0, 2) # LND -> NLD 230 | 231 | x = self.ln_post(x[:, 0, :]) 232 | 233 | if self.proj is not None: 234 | x = x @ self.proj 235 | 236 | return x 237 | 238 | 239 | class CLIP(nn.Module): 240 | def __init__(self, 241 | embed_dim: int, 242 | # vision 243 | image_resolution: int, 244 | vision_layers: Union[Tuple[int, int, int, int], int], 245 | vision_width: int, 246 | vision_patch_size: int, 247 | # text 248 | context_length: int, 249 | vocab_size: int, 250 | transformer_width: int, 251 | transformer_heads: int, 252 | transformer_layers: int 253 | ): 254 | super().__init__() 255 | 256 | self.context_length = context_length 257 | 258 | if isinstance(vision_layers, (tuple, list)): 259 | vision_heads = vision_width * 32 // 64 260 | self.visual = ModifiedResNet( 261 | layers=vision_layers, 262 | output_dim=embed_dim, 263 | heads=vision_heads, 264 | input_resolution=image_resolution, 265 | width=vision_width 266 | ) 267 | else: 268 | vision_heads = vision_width // 64 269 | self.visual = VisionTransformer( 270 | input_resolution=image_resolution, 271 | patch_size=vision_patch_size, 272 | width=vision_width, 273 | layers=vision_layers, 274 | heads=vision_heads, 275 | output_dim=embed_dim 276 | ) 277 | 278 | self.transformer = Transformer( 279 | width=transformer_width, 280 | layers=transformer_layers, 281 | heads=transformer_heads, 282 | attn_mask=self.build_attention_mask() 283 | ) 284 | 285 | self.vocab_size = vocab_size 286 | self.token_embedding = nn.Embedding(vocab_size, transformer_width) 287 | self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) 288 | self.ln_final = LayerNorm(transformer_width) 289 | 290 | self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) 291 | self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) 292 | 293 | self.initialize_parameters() 294 | 295 | def initialize_parameters(self): 296 | nn.init.normal_(self.token_embedding.weight, std=0.02) 297 | nn.init.normal_(self.positional_embedding, std=0.01) 298 | 299 | if isinstance(self.visual, ModifiedResNet): 300 | if self.visual.attnpool is not None: 301 | std = self.visual.attnpool.c_proj.in_features ** -0.5 302 | nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std) 303 | nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std) 304 | nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std) 305 | nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std) 306 | 307 | for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]: 308 | for name, param in resnet_block.named_parameters(): 309 | if name.endswith("bn3.weight"): 310 | nn.init.zeros_(param) 311 | 312 | proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) 313 | attn_std = self.transformer.width ** -0.5 314 | fc_std = (2 * self.transformer.width) ** -0.5 315 | for block in self.transformer.resblocks: 316 | nn.init.normal_(block.attn.in_proj_weight, std=attn_std) 317 | nn.init.normal_(block.attn.out_proj.weight, std=proj_std) 318 | nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) 319 | nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) 320 | 321 | if self.text_projection is not None: 322 | nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) 323 | 324 | def build_attention_mask(self): 325 | # lazily create causal attention mask, with full attention between the vision tokens 326 | # pytorch uses additive attention mask; fill with -inf 327 | mask = torch.empty(self.context_length, self.context_length) 328 | mask.fill_(float("-inf")) 329 | mask.triu_(1) # zero out the lower diagonal 330 | return mask 331 | 332 | @property 333 | def dtype(self): 334 | #return self.visual.conv1.weight.dtype 335 | # saves some memory since we don't need the visual part 336 | return torch.float16 337 | 338 | def encode_image(self, image): 339 | return self.visual(image.type(self.dtype)) 340 | 341 | def encode_text(self, text): 342 | x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model] 343 | 344 | x = x + self.positional_embedding.type(self.dtype) 345 | x = x.permute(1, 0, 2) # NLD -> LND 346 | x = self.transformer(x) 347 | x = x.permute(1, 0, 2) # LND -> NLD 348 | x = self.ln_final(x).type(self.dtype) 349 | 350 | # x.shape = [batch_size, n_ctx, transformer.width] 351 | # take features from the eot embedding (eot_token is the highest number in each sequence) 352 | x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection 353 | 354 | return x 355 | 356 | def forward(self, image, text): 357 | image_features = self.encode_image(image) 358 | text_features = self.encode_text(text) 359 | 360 | # normalized features 361 | image_features = image_features / image_features.norm(dim=-1, keepdim=True) 362 | text_features = text_features / text_features.norm(dim=-1, keepdim=True) 363 | 364 | # cosine similarity as logits 365 | logit_scale = self.logit_scale.exp() 366 | logits_per_image = logit_scale * image_features @ text_features.t() 367 | logits_per_text = logits_per_image.t() 368 | 369 | # shape = [global_batch_size, global_batch_size] 370 | return logits_per_image, logits_per_text 371 | 372 | 373 | def convert_weights(model: nn.Module): 374 | """Convert applicable model parameters to fp16""" 375 | 376 | def _convert_weights_to_fp16(l): 377 | if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): 378 | l.weight.data = l.weight.data.half() 379 | if l.bias is not None: 380 | l.bias.data = l.bias.data.half() 381 | 382 | if isinstance(l, nn.MultiheadAttention): 383 | for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: 384 | tensor = getattr(l, attr) 385 | if tensor is not None: 386 | tensor.data = tensor.data.half() 387 | 388 | for name in ["text_projection", "proj"]: 389 | if hasattr(l, name): 390 | attr = getattr(l, name) 391 | if attr is not None: 392 | attr.data = attr.data.half() 393 | 394 | model.apply(_convert_weights_to_fp16) 395 | 396 | 397 | def build_model(state_dict: dict): 398 | vit = "visual.proj" in state_dict 399 | 400 | if vit: 401 | vision_width = state_dict["visual.conv1.weight"].shape[0] 402 | vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) 403 | vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] 404 | grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) 405 | image_resolution = vision_patch_size * grid_size 406 | else: 407 | counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]] 408 | vision_layers = tuple(counts) 409 | vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] 410 | output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) 411 | vision_patch_size = None 412 | assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] 413 | image_resolution = output_width * 32 414 | 415 | embed_dim = state_dict["text_projection"].shape[1] 416 | context_length = state_dict["positional_embedding"].shape[0] 417 | vocab_size = state_dict["token_embedding.weight"].shape[0] 418 | transformer_width = state_dict["ln_final.weight"].shape[0] 419 | transformer_heads = transformer_width // 64 420 | transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks"))) 421 | 422 | model = CLIP( 423 | embed_dim, 424 | image_resolution, vision_layers, vision_width, vision_patch_size, 425 | context_length, vocab_size, transformer_width, transformer_heads, transformer_layers 426 | ) 427 | 428 | for key in ["input_resolution", "context_length", "vocab_size"]: 429 | if key in state_dict: 430 | del state_dict[key] 431 | 432 | convert_weights(model) 433 | model.load_state_dict(state_dict) 434 | return model.eval() 435 | -------------------------------------------------------------------------------- /clip_custom/simple_tokenizer.py: -------------------------------------------------------------------------------- 1 | import gzip 2 | import html 3 | import os 4 | from functools import lru_cache 5 | 6 | import ftfy 7 | import regex as re 8 | 9 | 10 | @lru_cache() 11 | def default_bpe(): 12 | return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz") 13 | 14 | 15 | @lru_cache() 16 | def bytes_to_unicode(): 17 | """ 18 | Returns list of utf-8 byte and a corresponding list of unicode strings. 19 | The reversible bpe codes work on unicode strings. 20 | This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. 21 | When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. 22 | This is a signficant percentage of your normal, say, 32K bpe vocab. 23 | To avoid that, we want lookup tables between utf-8 bytes and unicode strings. 24 | And avoids mapping to whitespace/control characters the bpe code barfs on. 25 | """ 26 | bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) 27 | cs = bs[:] 28 | n = 0 29 | for b in range(2**8): 30 | if b not in bs: 31 | bs.append(b) 32 | cs.append(2**8+n) 33 | n += 1 34 | cs = [chr(n) for n in cs] 35 | return dict(zip(bs, cs)) 36 | 37 | 38 | def get_pairs(word): 39 | """Return set of symbol pairs in a word. 40 | Word is represented as tuple of symbols (symbols being variable-length strings). 41 | """ 42 | pairs = set() 43 | prev_char = word[0] 44 | for char in word[1:]: 45 | pairs.add((prev_char, char)) 46 | prev_char = char 47 | return pairs 48 | 49 | 50 | def basic_clean(text): 51 | text = ftfy.fix_text(text) 52 | text = html.unescape(html.unescape(text)) 53 | return text.strip() 54 | 55 | 56 | def whitespace_clean(text): 57 | text = re.sub(r'\s+', ' ', text) 58 | text = text.strip() 59 | return text 60 | 61 | 62 | class SimpleTokenizer(object): 63 | def __init__(self, bpe_path: str = default_bpe()): 64 | self.byte_encoder = bytes_to_unicode() 65 | self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} 66 | merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') 67 | merges = merges[1:49152-256-2+1] 68 | merges = [tuple(merge.split()) for merge in merges] 69 | vocab = list(bytes_to_unicode().values()) 70 | vocab = vocab + [v+'' for v in vocab] 71 | for merge in merges: 72 | vocab.append(''.join(merge)) 73 | vocab.extend(['<|startoftext|>', '<|endoftext|>']) 74 | self.encoder = dict(zip(vocab, range(len(vocab)))) 75 | self.decoder = {v: k for k, v in self.encoder.items()} 76 | self.bpe_ranks = dict(zip(merges, range(len(merges)))) 77 | self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'} 78 | self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE) 79 | 80 | def bpe(self, token): 81 | if token in self.cache: 82 | return self.cache[token] 83 | word = tuple(token[:-1]) + ( token[-1] + '',) 84 | pairs = get_pairs(word) 85 | 86 | if not pairs: 87 | return token+'' 88 | 89 | while True: 90 | bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf'))) 91 | if bigram not in self.bpe_ranks: 92 | break 93 | first, second = bigram 94 | new_word = [] 95 | i = 0 96 | while i < len(word): 97 | try: 98 | j = word.index(first, i) 99 | new_word.extend(word[i:j]) 100 | i = j 101 | except: 102 | new_word.extend(word[i:]) 103 | break 104 | 105 | if word[i] == first and i < len(word)-1 and word[i+1] == second: 106 | new_word.append(first+second) 107 | i += 2 108 | else: 109 | new_word.append(word[i]) 110 | i += 1 111 | new_word = tuple(new_word) 112 | word = new_word 113 | if len(word) == 1: 114 | break 115 | else: 116 | pairs = get_pairs(word) 117 | word = ' '.join(word) 118 | self.cache[token] = word 119 | return word 120 | 121 | def encode(self, text): 122 | bpe_tokens = [] 123 | text = whitespace_clean(basic_clean(text)).lower() 124 | for token in re.findall(self.pat, text): 125 | token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) 126 | bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) 127 | return bpe_tokens 128 | 129 | def decode(self, tokens): 130 | text = ''.join([self.decoder[token] for token in tokens]) 131 | text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('', ' ') 132 | return text 133 | -------------------------------------------------------------------------------- /datasets/README.md: -------------------------------------------------------------------------------- 1 | # Downloading datasets 2 | 3 | This directory includes instructions and scripts for downloading ImageNet and LSUN bedrooms for use in this codebase. 4 | 5 | ## Class-conditional ImageNet 6 | 7 | For our class-conditional models, we use the official ILSVRC2012 dataset with manual center cropping and downsampling. To obtain this dataset, navigate to [this page on image-net.org](http://www.image-net.org/challenges/LSVRC/2012/downloads) and sign in (or create an account if you do not already have one). Then click on the link reading "Training images (Task 1 & 2)". This is a 138GB tar file containing 1000 sub-tar files, one per class. 8 | 9 | Once the file is downloaded, extract it and look inside. You should see 1000 `.tar` files. You need to extract each of these, which may be impractical to do by hand on your operating system. To automate the process on a Unix-based system, you can `cd` into the directory and run this short shell script: 10 | 11 | ``` 12 | for file in *.tar; do tar xf "$file"; rm "$file"; done 13 | ``` 14 | 15 | This will extract and remove each tar file in turn. 16 | 17 | Once all of the images have been extracted, the resulting directory should be usable as a data directory (the `--data_dir` argument for the training script). The filenames should all start with WNID (class ids) followed by underscores, like `n01440764_2708.JPEG`. Conveniently (but not by accident) this is how the automated data-loader expects to discover class labels. 18 | 19 | ## LSUN bedroom 20 | 21 | To download and pre-process LSUN bedroom, clone [fyu/lsun](https://github.com/fyu/lsun) on GitHub and run their download script `python3 download.py bedroom`. The result will be an "lmdb" database named like `bedroom_train_lmdb`. You can pass this to our [lsun_bedroom.py](lsun_bedroom.py) script like so: 22 | 23 | ``` 24 | python lsun_bedroom.py bedroom_train_lmdb lsun_train_output_dir 25 | ``` 26 | 27 | This creates a directory called `lsun_train_output_dir`. This directory can be passed to the training scripts via the `--data_dir` argument. 28 | -------------------------------------------------------------------------------- /datasets/lsun_bedroom.py: -------------------------------------------------------------------------------- 1 | """ 2 | Convert an LSUN lmdb database into a directory of images. 3 | """ 4 | 5 | import argparse 6 | import io 7 | import os 8 | 9 | from PIL import Image 10 | import lmdb 11 | import numpy as np 12 | 13 | 14 | def read_images(lmdb_path, image_size): 15 | env = lmdb.open(lmdb_path, map_size=1099511627776, max_readers=100, readonly=True) 16 | with env.begin(write=False) as transaction: 17 | cursor = transaction.cursor() 18 | for _, webp_data in cursor: 19 | img = Image.open(io.BytesIO(webp_data)) 20 | width, height = img.size 21 | scale = image_size / min(width, height) 22 | img = img.resize( 23 | (int(round(scale * width)), int(round(scale * height))), 24 | resample=Image.BOX, 25 | ) 26 | arr = np.array(img) 27 | h, w, _ = arr.shape 28 | h_off = (h - image_size) // 2 29 | w_off = (w - image_size) // 2 30 | arr = arr[h_off : h_off + image_size, w_off : w_off + image_size] 31 | yield arr 32 | 33 | 34 | def dump_images(out_dir, images, prefix): 35 | if not os.path.exists(out_dir): 36 | os.mkdir(out_dir) 37 | for i, img in enumerate(images): 38 | Image.fromarray(img).save(os.path.join(out_dir, f"{prefix}_{i:07d}.png")) 39 | 40 | 41 | def main(): 42 | parser = argparse.ArgumentParser() 43 | parser.add_argument("--image-size", help="new image size", type=int, default=256) 44 | parser.add_argument("--prefix", help="class name", type=str, default="bedroom") 45 | parser.add_argument("lmdb_path", help="path to an LSUN lmdb database") 46 | parser.add_argument("out_dir", help="path to output directory") 47 | args = parser.parse_args() 48 | 49 | images = read_images(args.lmdb_path, args.image_size) 50 | dump_images(args.out_dir, images, args.prefix) 51 | 52 | 53 | if __name__ == "__main__": 54 | main() 55 | -------------------------------------------------------------------------------- /encoders/modules.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from functools import partial 4 | 5 | from encoders.x_transformer import Encoder, TransformerWrapper # TODO: can we directly rely on lucidrains code and simply add this as a reuirement? --> test 6 | 7 | 8 | class AbstractEncoder(nn.Module): 9 | def __init__(self): 10 | super().__init__() 11 | 12 | def encode(self, *args, **kwargs): 13 | raise NotImplementedError 14 | 15 | 16 | 17 | class ClassEmbedder(nn.Module): 18 | def __init__(self, embed_dim, n_classes=1000, key='class'): 19 | super().__init__() 20 | self.key = key 21 | self.embedding = nn.Embedding(n_classes, embed_dim) 22 | 23 | def forward(self, batch, key=None): 24 | if key is None: 25 | key = self.key 26 | # this is for use in crossattn 27 | c = batch[key][:, None] 28 | c = self.embedding(c) 29 | return c 30 | 31 | 32 | class TransformerEmbedder(AbstractEncoder): 33 | """Some transformer encoder layers""" 34 | def __init__(self, n_embed, n_layer, vocab_size, max_seq_len=77, device="cuda"): 35 | super().__init__() 36 | self.device = device 37 | self.transformer = TransformerWrapper(num_tokens=vocab_size, max_seq_len=max_seq_len, 38 | attn_layers=Encoder(dim=n_embed, depth=n_layer)) 39 | 40 | def forward(self, tokens): 41 | tokens = tokens.to(self.device) # meh 42 | z = self.transformer(tokens, return_embeddings=True) 43 | return z 44 | 45 | def encode(self, x): 46 | return self(x) 47 | 48 | 49 | class BERTTokenizer(AbstractEncoder): 50 | """ Uses a pretrained BERT tokenizer by huggingface. Vocab size: 30522 (?)""" 51 | def __init__(self, device="cuda", vq_interface=True, max_length=77): 52 | super().__init__() 53 | from transformers import BertTokenizerFast # TODO: add to reuquirements 54 | self.tokenizer = BertTokenizerFast.from_pretrained("bert-base-uncased") 55 | self.device = device 56 | self.vq_interface = vq_interface 57 | self.max_length = max_length 58 | 59 | def forward(self, text): 60 | batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True, 61 | return_overflowing_tokens=False, padding="max_length", return_tensors="pt") 62 | tokens = batch_encoding["input_ids"].to(self.device) 63 | return tokens 64 | 65 | @torch.no_grad() 66 | def encode(self, text): 67 | tokens = self(text) 68 | if not self.vq_interface: 69 | return tokens 70 | return None, None, [None, None, tokens] 71 | 72 | def decode(self, text): 73 | return text 74 | 75 | 76 | class BERTEmbedder(AbstractEncoder): 77 | """Uses the BERT tokenizr model and add some transformer encoder layers""" 78 | def __init__(self, n_embed, n_layer, vocab_size=30522, max_seq_len=77, 79 | device="cuda",use_tokenizer=True, embedding_dropout=0.0): 80 | super().__init__() 81 | self.use_tknz_fn = use_tokenizer 82 | if self.use_tknz_fn: 83 | self.tknz_fn = BERTTokenizer(vq_interface=False, max_length=max_seq_len) 84 | self.device = device 85 | self.transformer = TransformerWrapper(num_tokens=vocab_size, max_seq_len=max_seq_len, 86 | attn_layers=Encoder(dim=n_embed, depth=n_layer), 87 | emb_dropout=embedding_dropout) 88 | 89 | def forward(self, text): 90 | if self.use_tknz_fn: 91 | tokens = self.tknz_fn(text)#.to(self.device) 92 | else: 93 | tokens = text 94 | z = self.transformer(tokens, return_embeddings=True) 95 | return z 96 | 97 | def encode(self, text): 98 | # output of length 77 99 | return self(text) 100 | 101 | 102 | class SpatialRescaler(nn.Module): 103 | def __init__(self, 104 | n_stages=1, 105 | method='bilinear', 106 | multiplier=0.5, 107 | in_channels=3, 108 | out_channels=None, 109 | bias=False): 110 | super().__init__() 111 | self.n_stages = n_stages 112 | assert self.n_stages >= 0 113 | assert method in ['nearest','linear','bilinear','trilinear','bicubic','area'] 114 | self.multiplier = multiplier 115 | self.interpolator = partial(torch.nn.functional.interpolate, mode=method) 116 | self.remap_output = out_channels is not None 117 | if self.remap_output: 118 | print(f'Spatial Rescaler mapping from {in_channels} to {out_channels} channels after resizing.') 119 | self.channel_mapper = nn.Conv2d(in_channels,out_channels,1,bias=bias) 120 | 121 | def forward(self,x): 122 | for stage in range(self.n_stages): 123 | x = self.interpolator(x, scale_factor=self.multiplier) 124 | 125 | 126 | if self.remap_output: 127 | x = self.channel_mapper(x) 128 | return x 129 | 130 | def encode(self, x): 131 | return self(x) 132 | -------------------------------------------------------------------------------- /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 | * ImageNet 64x64: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/64/VIRTUAL_imagenet64_labeled.npz) 26 | * [ADM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/64/admnet_imagenet64.npz) 27 | * [IDDPM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/64/iddpm_imagenet64.npz) 28 | * [BigGAN](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/64/biggan_deep_imagenet64.npz) 29 | * ImageNet 128x128: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/128/VIRTUAL_imagenet128_labeled.npz) 30 | * [ADM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/128/admnet_imagenet128.npz) 31 | * [ADM-G](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/128/admnet_guided_imagenet128.npz) 32 | * [ADM-G, 25 steps](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/128/admnet_guided_25step_imagenet128.npz) 33 | * [BigGAN-deep (trunc=1.0)](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/128/biggan_deep_trunc1_imagenet128.npz) 34 | * ImageNet 256x256: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/VIRTUAL_imagenet256_labeled.npz) 35 | * [ADM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/admnet_imagenet256.npz) 36 | * [ADM-G](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/admnet_guided_imagenet256.npz) 37 | * [ADM-G, 25 step](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/admnet_guided_25step_imagenet256.npz) 38 | * [ADM-G + ADM-U](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/admnet_guided_upsampled_imagenet256.npz) 39 | * [ADM-U](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/admnet_upsampled_imagenet256.npz) 40 | * [BigGAN-deep (trunc=1.0)](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/biggan_deep_trunc1_imagenet256.npz) 41 | * ImageNet 512x512: [reference batch](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/VIRTUAL_imagenet512.npz) 42 | * [ADM](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/admnet_imagenet512.npz) 43 | * [ADM-G](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/admnet_guided_imagenet512.npz) 44 | * [ADM-G, 25 step](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/admnet_guided_25step_imagenet512.npz) 45 | * [ADM-G + ADM-U](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/admnet_guided_upsampled_imagenet512.npz) 46 | * [ADM-U](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/admnet_upsampled_imagenet512.npz) 47 | * [BigGAN-deep (trunc=1.0)](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/512/biggan_deep_trunc1_imagenet512.npz) 48 | 49 | # Run evaluations 50 | 51 | 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`. 52 | 53 | 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. 54 | 55 | The output of the script will look something like this, where the first `...` is a bunch of verbose TensorFlow logging: 56 | 57 | ``` 58 | $ python evaluator.py VIRTUAL_imagenet256_labeled.npz admnet_guided_upsampled_imagenet256.npz 59 | ... 60 | computing reference batch activations... 61 | computing/reading reference batch statistics... 62 | computing sample batch activations... 63 | computing/reading sample batch statistics... 64 | Computing evaluations... 65 | Inception Score: 215.8370361328125 66 | FID: 3.9425574129223264 67 | sFID: 6.140433703346162 68 | Precision: 0.8265 69 | Recall: 0.5309 70 | ``` 71 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | # th.cuda.set_device(MPI.COMM_WORLD.Get_rank()) 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 | with bf.BlobFile(path, "rb") as f: data = f.read() 57 | return th.load(io.BytesIO(data), **kwargs) 58 | 59 | 60 | def sync_params(params): 61 | """ 62 | Synchronize a sequence of Tensors across ranks from rank 0. 63 | """ 64 | for p in params: 65 | with th.no_grad(): 66 | dist.broadcast(p, 0) 67 | 68 | 69 | def _find_free_port(): 70 | try: 71 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 72 | s.bind(("", 0)) 73 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 74 | return s.getsockname()[1] 75 | finally: 76 | s.close() 77 | -------------------------------------------------------------------------------- /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/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 | def load_data( 11 | *, 12 | data_dir, 13 | batch_size, 14 | image_size, 15 | class_cond=False, 16 | deterministic=False, 17 | random_crop=False, 18 | random_flip=True, 19 | ): 20 | """ 21 | For a dataset, create a generator over (images, kwargs) pairs. 22 | 23 | Each images is an NCHW float tensor, and the kwargs dict contains zero or 24 | more keys, each of which map to a batched Tensor of their own. 25 | The kwargs dict can be used for class labels, in which case the key is "y" 26 | and the values are integer tensors of class labels. 27 | 28 | :param data_dir: a dataset directory. 29 | :param batch_size: the batch size of each returned pair. 30 | :param image_size: the size to which images are resized. 31 | :param class_cond: if True, include a "y" key in returned dicts for class 32 | label. If classes are not available and this is true, an 33 | exception will be raised. 34 | :param deterministic: if True, yield results in a deterministic order. 35 | :param random_crop: if True, randomly crop the images for augmentation. 36 | :param random_flip: if True, randomly flip the images for augmentation. 37 | """ 38 | if not data_dir: 39 | raise ValueError("unspecified data directory") 40 | all_files = _list_image_files_recursively(data_dir) 41 | classes = None 42 | if class_cond: 43 | # Assume classes are the first part of the filename, 44 | # before an underscore. 45 | class_names = [bf.basename(path).split("_")[0] for path in all_files] 46 | sorted_classes = {x: i for i, x in enumerate(sorted(set(class_names)))} 47 | classes = [sorted_classes[x] for x in class_names] 48 | dataset = ImageDataset( 49 | image_size, 50 | all_files, 51 | classes=classes, 52 | shard=MPI.COMM_WORLD.Get_rank(), 53 | num_shards=MPI.COMM_WORLD.Get_size(), 54 | random_crop=random_crop, 55 | random_flip=random_flip, 56 | ) 57 | if deterministic: 58 | loader = DataLoader( 59 | dataset, batch_size=batch_size, shuffle=False, num_workers=1, drop_last=True 60 | ) 61 | else: 62 | loader = DataLoader( 63 | dataset, batch_size=batch_size, shuffle=True, num_workers=1, drop_last=True 64 | ) 65 | while True: 66 | yield from loader 67 | 68 | 69 | def _list_image_files_recursively(data_dir): 70 | results = [] 71 | for entry in sorted(bf.listdir(data_dir)): 72 | full_path = bf.join(data_dir, entry) 73 | ext = entry.split(".")[-1] 74 | if "." in entry and ext.lower() in ["jpg", "jpeg", "png", "gif", "webp"]: 75 | results.append(full_path) 76 | elif bf.isdir(full_path): 77 | results.extend(_list_image_files_recursively(full_path)) 78 | return results 79 | 80 | 81 | class ImageDataset(Dataset): 82 | def __init__( 83 | self, 84 | resolution, 85 | image_paths, 86 | classes=None, 87 | shard=0, 88 | num_shards=1, 89 | random_crop=False, 90 | random_flip=True, 91 | ): 92 | super().__init__() 93 | self.resolution = resolution 94 | self.local_images = image_paths[shard:][::num_shards] 95 | self.local_classes = None if classes is None else classes[shard:][::num_shards] 96 | self.random_crop = random_crop 97 | self.random_flip = random_flip 98 | 99 | def __len__(self): 100 | return len(self.local_images) 101 | 102 | def __getitem__(self, idx): 103 | path = self.local_images[idx] 104 | with bf.BlobFile(path, "rb") as f: 105 | pil_image = Image.open(f) 106 | pil_image.load() 107 | pil_image = pil_image.convert("RGB") 108 | 109 | if self.random_crop: 110 | arr = random_crop_arr(pil_image, self.resolution) 111 | else: 112 | arr = center_crop_arr(pil_image, self.resolution) 113 | 114 | if self.random_flip and random.random() < 0.5: 115 | arr = arr[:, ::-1] 116 | 117 | arr = arr.astype(np.float32) / 127.5 - 1 118 | 119 | out_dict = {} 120 | if self.local_classes is not None: 121 | out_dict["y"] = np.array(self.local_classes[idx], dtype=np.int64) 122 | return np.transpose(arr, [2, 0, 1]), out_dict 123 | 124 | 125 | def center_crop_arr(pil_image, image_size): 126 | # We are not on a new enough PIL to support the `reducing_gap` 127 | # argument, which uses BOX downsampling at powers of two first. 128 | # Thus, we do it by hand to improve downsample quality. 129 | while min(*pil_image.size) >= 2 * image_size: 130 | pil_image = pil_image.resize( 131 | tuple(x // 2 for x in pil_image.size), resample=Image.BOX 132 | ) 133 | 134 | scale = image_size / min(*pil_image.size) 135 | pil_image = pil_image.resize( 136 | tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC 137 | ) 138 | 139 | arr = np.array(pil_image) 140 | crop_y = (arr.shape[0] - image_size) // 2 141 | crop_x = (arr.shape[1] - image_size) // 2 142 | return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size] 143 | 144 | 145 | def random_crop_arr(pil_image, image_size, min_crop_frac=0.8, max_crop_frac=1.0): 146 | min_smaller_dim_size = math.ceil(image_size / max_crop_frac) 147 | max_smaller_dim_size = math.ceil(image_size / min_crop_frac) 148 | smaller_dim_size = random.randrange(min_smaller_dim_size, max_smaller_dim_size + 1) 149 | 150 | # We are not on a new enough PIL to support the `reducing_gap` 151 | # argument, which uses BOX downsampling at powers of two first. 152 | # Thus, we do it by hand to improve downsample quality. 153 | while min(*pil_image.size) >= 2 * smaller_dim_size: 154 | pil_image = pil_image.resize( 155 | tuple(x // 2 for x in pil_image.size), resample=Image.BOX 156 | ) 157 | 158 | scale = smaller_dim_size / min(*pil_image.size) 159 | pil_image = pil_image.resize( 160 | tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC 161 | ) 162 | 163 | arr = np.array(pil_image) 164 | crop_y = random.randrange(arr.shape[0] - image_size + 1) 165 | crop_x = random.randrange(arr.shape[1] - image_size + 1) 166 | return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size] 167 | -------------------------------------------------------------------------------- /guided_diffusion/image_text_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 | def load_data( 11 | *, 12 | data_dir, 13 | batch_size, 14 | image_size, 15 | class_cond=False, 16 | deterministic=False, 17 | random_crop=False, 18 | random_flip=True, 19 | ): 20 | """ 21 | For a dataset, create a generator over (images, kwargs) pairs. 22 | 23 | Each images is an NCHW float tensor, and the kwargs dict contains zero or 24 | more keys, each of which map to a batched Tensor of their own. 25 | The kwargs dict can be used for class labels, in which case the key is "y" 26 | and the values are integer tensors of class labels. 27 | 28 | :param data_dir: a dataset directory. 29 | :param batch_size: the batch size of each returned pair. 30 | :param image_size: the size to which images are resized. 31 | :param class_cond: if True, include a "y" key in returned dicts for class 32 | label. If classes are not available and this is true, an 33 | exception will be raised. 34 | :param deterministic: if True, yield results in a deterministic order. 35 | :param random_crop: if True, randomly crop the images for augmentation. 36 | :param random_flip: if True, randomly flip the images for augmentation. 37 | """ 38 | if not data_dir: 39 | raise ValueError("unspecified data directory") 40 | all_files = _list_image_files_recursively(data_dir) 41 | classes = None 42 | #if class_cond: 43 | # Assume classes are the first part of the filename, 44 | # before an underscore. 45 | # class_names = [bf.basename(path).split("_")[0] for path in all_files] 46 | # sorted_classes = {x: i for i, x in enumerate(sorted(set(class_names)))} 47 | # classes = [sorted_classes[x] for x in class_names] 48 | dataset = ImageDataset( 49 | image_size, 50 | all_files, 51 | classes=classes, 52 | shard=MPI.COMM_WORLD.Get_rank(), 53 | num_shards=MPI.COMM_WORLD.Get_size(), 54 | random_crop=random_crop, 55 | random_flip=random_flip, 56 | ) 57 | if deterministic: 58 | loader = DataLoader( 59 | dataset, batch_size=batch_size, shuffle=False, num_workers=1, drop_last=True 60 | ) 61 | else: 62 | loader = DataLoader( 63 | dataset, batch_size=batch_size, shuffle=True, num_workers=1, drop_last=True 64 | ) 65 | while True: 66 | yield from loader 67 | 68 | 69 | def _list_image_files_recursively(data_dir): 70 | results = [] 71 | for entry in sorted(bf.listdir(data_dir)): 72 | full_path = bf.join(data_dir, entry) 73 | entry = entry.split(".") 74 | ext = entry[-1].strip() 75 | filename = entry[0] 76 | if ext and ext.lower() in ["jpg", "jpeg", "png", "gif", "webp"]: 77 | text_path = bf.join(data_dir, filename+'.txt') 78 | if bf.exists(text_path): 79 | results.append((full_path, text_path)) 80 | elif bf.isdir(full_path): 81 | results.extend(_list_image_files_recursively(full_path)) 82 | return results 83 | 84 | 85 | class ImageDataset(Dataset): 86 | def __init__( 87 | self, 88 | resolution, 89 | file_paths, 90 | classes=None, 91 | shard=0, 92 | num_shards=1, 93 | random_crop=False, 94 | random_flip=True, 95 | ): 96 | super().__init__() 97 | self.resolution = resolution 98 | self.local_files = file_paths[shard:][::num_shards] 99 | self.local_classes = None if classes is None else classes[shard:][::num_shards] 100 | self.random_crop = random_crop 101 | self.random_flip = random_flip 102 | 103 | def __len__(self): 104 | return len(self.local_files) 105 | 106 | def __getitem__(self, idx): 107 | path = self.local_files[idx] 108 | with bf.BlobFile(path[0], "rb") as f: 109 | pil_image = Image.open(f) 110 | pil_image.load() 111 | pil_image = pil_image.convert("RGB") 112 | 113 | if self.random_crop: 114 | arr = random_crop_arr(pil_image, self.resolution) 115 | else: 116 | arr = center_crop_arr(pil_image, self.resolution) 117 | 118 | if self.random_flip and random.random() < 0.5: 119 | arr = arr[:, ::-1] 120 | 121 | arr = arr.astype(np.float32) / 127.5 - 1 122 | 123 | out_dict = {} 124 | if self.local_classes is not None: 125 | out_dict["y"] = np.array(self.local_classes[idx], dtype=np.int64) 126 | 127 | with bf.BlobFile(path[1], "r") as f: 128 | text = f.read().strip() 129 | 130 | return np.transpose(arr, [2, 0, 1]), out_dict, text 131 | 132 | 133 | def center_crop_arr(pil_image, image_size): 134 | # We are not on a new enough PIL to support the `reducing_gap` 135 | # argument, which uses BOX downsampling at powers of two first. 136 | # Thus, we do it by hand to improve downsample quality. 137 | while min(*pil_image.size) >= 2 * image_size: 138 | pil_image = pil_image.resize( 139 | tuple(x // 2 for x in pil_image.size), resample=Image.BOX 140 | ) 141 | 142 | scale = image_size / min(*pil_image.size) 143 | pil_image = pil_image.resize( 144 | tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC 145 | ) 146 | 147 | arr = np.array(pil_image) 148 | crop_y = (arr.shape[0] - image_size) // 2 149 | crop_x = (arr.shape[1] - image_size) // 2 150 | return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size] 151 | 152 | 153 | def random_crop_arr(pil_image, image_size, min_crop_frac=0.8, max_crop_frac=1.0): 154 | min_smaller_dim_size = math.ceil(image_size / max_crop_frac) 155 | max_smaller_dim_size = math.ceil(image_size / min_crop_frac) 156 | smaller_dim_size = random.randrange(min_smaller_dim_size, max_smaller_dim_size + 1) 157 | 158 | # We are not on a new enough PIL to support the `reducing_gap` 159 | # argument, which uses BOX downsampling at powers of two first. 160 | # Thus, we do it by hand to improve downsample quality. 161 | while min(*pil_image.size) >= 2 * smaller_dim_size: 162 | pil_image = pil_image.resize( 163 | tuple(x // 2 for x in pil_image.size), resample=Image.BOX 164 | ) 165 | 166 | scale = smaller_dim_size / min(*pil_image.size) 167 | pil_image = pil_image.resize( 168 | tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC 169 | ) 170 | 171 | arr = np.array(pil_image) 172 | crop_y = random.randrange(arr.shape[0] - image_size + 1) 173 | crop_x = random.randrange(arr.shape[1] - image_size + 1) 174 | return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size] 175 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | import torch.nn.functional as F 10 | 11 | class GroupNorm32(nn.GroupNorm): 12 | def __init__(self, num_groups, num_channels, swish, eps=1e-5): 13 | super().__init__(num_groups=num_groups, num_channels=num_channels, eps=eps) 14 | self.swish = swish 15 | 16 | def forward(self, x): 17 | y = super().forward(x.float()).to(x.dtype) 18 | if self.swish == 1.0: 19 | y = F.silu(y) 20 | elif self.swish: 21 | y = y * F.sigmoid(y * float(self.swish)) 22 | return y 23 | 24 | def conv_nd(dims, *args, **kwargs): 25 | """ 26 | Create a 1D, 2D, or 3D convolution module. 27 | """ 28 | if dims == 1: 29 | return nn.Conv1d(*args, **kwargs) 30 | elif dims == 2: 31 | return nn.Conv2d(*args, **kwargs) 32 | elif dims == 3: 33 | return nn.Conv3d(*args, **kwargs) 34 | raise ValueError(f"unsupported dimensions: {dims}") 35 | 36 | 37 | def linear(*args, **kwargs): 38 | """ 39 | Create a linear module. 40 | """ 41 | return nn.Linear(*args, **kwargs) 42 | 43 | 44 | def avg_pool_nd(dims, *args, **kwargs): 45 | """ 46 | Create a 1D, 2D, or 3D average pooling module. 47 | """ 48 | if dims == 1: 49 | return nn.AvgPool1d(*args, **kwargs) 50 | elif dims == 2: 51 | return nn.AvgPool2d(*args, **kwargs) 52 | elif dims == 3: 53 | return nn.AvgPool3d(*args, **kwargs) 54 | raise ValueError(f"unsupported dimensions: {dims}") 55 | 56 | 57 | def update_ema(target_params, source_params, rate=0.99): 58 | """ 59 | Update target parameters to be closer to those of source parameters using 60 | an exponential moving average. 61 | 62 | :param target_params: the target parameter sequence. 63 | :param source_params: the source parameter sequence. 64 | :param rate: the EMA rate (closer to 1 means slower). 65 | """ 66 | for targ, src in zip(target_params, source_params): 67 | targ.detach().mul_(rate).add_(src, alpha=1 - rate) 68 | 69 | 70 | def zero_module(module): 71 | """ 72 | Zero out the parameters of a module and return it. 73 | """ 74 | for p in module.parameters(): 75 | p.detach().zero_() 76 | return module 77 | 78 | 79 | def scale_module(module, scale): 80 | """ 81 | Scale the parameters of a module and return it. 82 | """ 83 | for p in module.parameters(): 84 | p.detach().mul_(scale) 85 | return module 86 | 87 | 88 | def mean_flat(tensor): 89 | """ 90 | Take the mean over all non-batch dimensions. 91 | """ 92 | return tensor.mean(dim=list(range(1, len(tensor.shape)))) 93 | 94 | 95 | def normalization(channels, swish=0.0): 96 | """ 97 | Make a standard normalization layer, with an optional swish activation. 98 | 99 | :param channels: number of input channels. 100 | :return: an nn.Module for normalization. 101 | """ 102 | return GroupNorm32(num_channels=channels, num_groups=32, swish=swish) 103 | 104 | 105 | #def timestep_embedding(timesteps, dim, max_period=10000): 106 | # """ 107 | # Create sinusoidal timestep embeddings. 108 | 109 | # :param timesteps: a 1-D Tensor of N indices, one per batch element. 110 | # These may be fractional. 111 | # :param dim: the dimension of the output. 112 | # :param max_period: controls the minimum frequency of the embeddings. 113 | # :return: an [N x dim] Tensor of positional embeddings. 114 | # """ 115 | # half = dim // 2 116 | # freqs = th.exp( 117 | # -math.log(max_period) * th.arange(start=0, end=half, dtype=th.float32) / half 118 | # ).to(device=timesteps.device) 119 | # args = timesteps[:, None].float() * freqs[None] 120 | # embedding = th.cat([th.cos(args), th.sin(args)], dim=-1) 121 | # if dim % 2: 122 | # embedding = th.cat([embedding, th.zeros_like(embedding[:, :1])], dim=-1) 123 | # return embedding 124 | 125 | def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False): 126 | """ 127 | Create sinusoidal timestep embeddings. 128 | :param timesteps: a 1-D Tensor of N indices, one per batch element. 129 | These may be fractional. 130 | :param dim: the dimension of the output. 131 | :param max_period: controls the minimum frequency of the embeddings. 132 | :return: an [N x dim] Tensor of positional embeddings. 133 | """ 134 | if not repeat_only: 135 | half = dim // 2 136 | freqs = th.exp( 137 | -math.log(max_period) * th.arange(start=0, end=half, dtype=th.float32) / half 138 | ).to(device=timesteps.device) 139 | args = timesteps[:, None].float() * freqs[None] 140 | embedding = th.cat([th.cos(args), th.sin(args)], dim=-1) 141 | if dim % 2: 142 | embedding = th.cat([embedding, th.zeros_like(embedding[:, :1])], dim=-1) 143 | else: 144 | embedding = repeat(timesteps, 'b -> b d', d=dim) 145 | return embedding 146 | 147 | 148 | 149 | def checkpoint(func, inputs, params, flag): 150 | """ 151 | Evaluate a function without caching intermediate activations, allowing for 152 | reduced memory at the expense of extra compute in the backward pass. 153 | 154 | :param func: the function to evaluate. 155 | :param inputs: the argument sequence to pass to `func`. 156 | :param params: a sequence of parameters `func` depends on but does not 157 | explicitly take as arguments. 158 | :param flag: if False, disable gradient checkpointing. 159 | """ 160 | if flag: 161 | args = tuple(inputs) + tuple(params) 162 | return CheckpointFunction.apply(func, len(inputs), *args) 163 | else: 164 | return func(*inputs) 165 | 166 | 167 | class CheckpointFunction(th.autograd.Function): 168 | @staticmethod 169 | def forward(ctx, run_function, length, *args): 170 | ctx.run_function = run_function 171 | ctx.input_tensors = list(args[:length]) 172 | ctx.input_params = list(args[length:]) 173 | with th.no_grad(): 174 | output_tensors = ctx.run_function(*ctx.input_tensors) 175 | return output_tensors 176 | 177 | @staticmethod 178 | def backward(ctx, *output_grads): 179 | ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] 180 | with th.enable_grad(): 181 | # Fixes a bug where the first op in run_function modifies the 182 | # Tensor storage in place, which is not allowed for detach()'d 183 | # Tensors. 184 | shallow_copies = [x.view_as(x) for x in ctx.input_tensors] 185 | output_tensors = ctx.run_function(*shallow_copies) 186 | input_grads = th.autograd.grad( 187 | output_tensors, 188 | ctx.input_tensors + ctx.input_params, 189 | output_grads, 190 | allow_unused=True, 191 | ) 192 | del ctx.input_tensors 193 | del ctx.input_params 194 | del output_tensors 195 | return (None, None) + input_grads 196 | -------------------------------------------------------------------------------- /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/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 get_eps(self, model, *args, **kwargs): 105 | return super().get_eps(self._wrap_model(model), *args, **kwargs) 106 | 107 | def _wrap_model(self, model): 108 | if isinstance(model, _WrappedModel): 109 | return model 110 | return _WrappedModel( 111 | model, self.timestep_map, self.rescale_timesteps, self.original_num_steps 112 | ) 113 | 114 | def _scale_timesteps(self, t): 115 | # Scaling is done by the wrapped model. 116 | return t 117 | 118 | 119 | class _WrappedModel: 120 | def __init__(self, model, timestep_map, rescale_timesteps, original_num_steps): 121 | self.model = model 122 | self.timestep_map = timestep_map 123 | self.rescale_timesteps = rescale_timesteps 124 | self.original_num_steps = original_num_steps 125 | 126 | def __call__(self, x, ts, **kwargs): 127 | ts = ts.float() 128 | frac = ts.frac() 129 | map_tensor = th.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype) 130 | new_ts_1 = map_tensor[ts.floor().long()] 131 | new_ts_2 = map_tensor[ts.ceil().long()] 132 | new_ts = th.lerp(new_ts_1, new_ts_2, frac) 133 | return self.model(x, new_ts, **kwargs) 134 | -------------------------------------------------------------------------------- /guided_diffusion/script_util.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import inspect 3 | 4 | from . import gaussian_diffusion as gd 5 | from .respace import SpacedDiffusion, space_timesteps 6 | from .unet import UNetModel 7 | 8 | NUM_CLASSES = 2 9 | 10 | 11 | def diffusion_defaults(): 12 | """ 13 | Defaults for image and classifier training. 14 | """ 15 | return dict( 16 | learn_sigma=False, 17 | diffusion_steps=1000, 18 | noise_schedule="linear", 19 | timestep_respacing="", 20 | use_kl=False, 21 | predict_xstart=False, 22 | rescale_timesteps=False, 23 | rescale_learned_sigmas=False, 24 | ) 25 | 26 | 27 | def classifier_defaults(): 28 | """ 29 | Defaults for classifier models. 30 | """ 31 | return dict( 32 | image_size=64, 33 | classifier_use_fp16=False, 34 | classifier_width=128, 35 | classifier_depth=2, 36 | classifier_attention_resolutions="32,16,8", # 16 37 | classifier_use_scale_shift_norm=True, # False 38 | classifier_resblock_updown=True, # False 39 | classifier_pool="attention", 40 | ) 41 | 42 | 43 | def model_and_diffusion_defaults(): 44 | """ 45 | Defaults for image training. 46 | """ 47 | res = dict( 48 | image_size=64, 49 | num_channels=128, 50 | num_res_blocks=2, 51 | num_heads=4, 52 | num_heads_upsample=-1, 53 | num_head_channels=-1, 54 | attention_resolutions="16,8", 55 | channel_mult="", 56 | dropout=0.0, 57 | class_cond=False, 58 | use_checkpoint=False, 59 | use_scale_shift_norm=True, 60 | resblock_updown=False, 61 | use_fp16=False, 62 | 63 | use_spatial_transformer=True, 64 | context_dim=1280, 65 | 66 | clip_embed_dim=None, 67 | image_condition=False, 68 | super_res_condition=False 69 | ) 70 | res.update(diffusion_defaults()) 71 | return res 72 | 73 | 74 | def classifier_and_diffusion_defaults(): 75 | res = classifier_defaults() 76 | res.update(diffusion_defaults()) 77 | return res 78 | 79 | 80 | def create_model_and_diffusion( 81 | image_size, 82 | class_cond, 83 | learn_sigma, 84 | num_channels, 85 | num_res_blocks, 86 | channel_mult, 87 | num_heads, 88 | num_head_channels, 89 | num_heads_upsample, 90 | attention_resolutions, 91 | dropout, 92 | diffusion_steps, 93 | noise_schedule, 94 | timestep_respacing, 95 | use_kl, 96 | predict_xstart, 97 | rescale_timesteps, 98 | rescale_learned_sigmas, 99 | use_checkpoint, 100 | use_scale_shift_norm, 101 | resblock_updown, 102 | use_fp16, 103 | use_spatial_transformer, 104 | context_dim, 105 | clip_embed_dim, 106 | image_condition, 107 | super_res_condition, 108 | ): 109 | model = create_model( 110 | image_size, 111 | num_channels, 112 | num_res_blocks, 113 | channel_mult=channel_mult, 114 | learn_sigma=learn_sigma, 115 | class_cond=class_cond, 116 | use_checkpoint=use_checkpoint, 117 | attention_resolutions=attention_resolutions, 118 | num_heads=num_heads, 119 | num_head_channels=num_head_channels, 120 | num_heads_upsample=num_heads_upsample, 121 | use_scale_shift_norm=use_scale_shift_norm, 122 | dropout=dropout, 123 | resblock_updown=resblock_updown, 124 | use_fp16=use_fp16, 125 | use_spatial_transformer=use_spatial_transformer, 126 | context_dim=context_dim, 127 | clip_embed_dim=clip_embed_dim, 128 | image_condition=image_condition, 129 | super_res_condition=super_res_condition, 130 | ) 131 | diffusion = create_gaussian_diffusion( 132 | steps=diffusion_steps, 133 | learn_sigma=learn_sigma, 134 | noise_schedule=noise_schedule, 135 | use_kl=use_kl, 136 | predict_xstart=predict_xstart, 137 | rescale_timesteps=rescale_timesteps, 138 | rescale_learned_sigmas=rescale_learned_sigmas, 139 | timestep_respacing=timestep_respacing, 140 | ) 141 | return model, diffusion 142 | 143 | 144 | def create_model( 145 | image_size, 146 | num_channels, 147 | num_res_blocks, 148 | channel_mult="", 149 | learn_sigma=False, 150 | class_cond=False, 151 | use_checkpoint=False, 152 | attention_resolutions="16", 153 | num_heads=1, 154 | num_head_channels=-1, 155 | num_heads_upsample=-1, 156 | use_scale_shift_norm=False, 157 | dropout=0, 158 | resblock_updown=False, 159 | use_fp16=False, 160 | use_spatial_transformer=True, 161 | context_dim=1280, 162 | clip_embed_dim=None, 163 | image_condition=False, 164 | super_res_condition=False 165 | ): 166 | if channel_mult == "": 167 | if image_size == 512: 168 | channel_mult = (0.5, 1, 1, 2, 2, 4, 4) 169 | elif image_size == 256: 170 | channel_mult = (1, 1, 2, 2, 4, 4) 171 | elif image_size == 128: 172 | channel_mult = (1, 1, 2, 3, 4) 173 | elif image_size == 64: 174 | channel_mult = (1, 2, 3, 4) 175 | elif image_size == 32: 176 | channel_mult = (1, 2, 4, 4) 177 | else: 178 | raise ValueError(f"unsupported image size: {image_size}") 179 | else: 180 | channel_mult = tuple(int(ch_mult) for ch_mult in channel_mult.split(",")) 181 | 182 | attention_ds = [] 183 | for res in attention_resolutions.split(","): 184 | attention_ds.append(image_size // int(res)) 185 | 186 | in_channels = 4 if image_size == 32 else 3 187 | out_channels = 4 188 | 189 | return UNetModel( 190 | image_size=image_size, 191 | in_channels=in_channels, 192 | model_channels=num_channels, 193 | out_channels=out_channels, 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_spatial_transformer=use_spatial_transformer, 207 | context_dim=context_dim, 208 | clip_embed_dim=clip_embed_dim, 209 | image_condition=image_condition, 210 | super_res_condition=super_res_condition, 211 | ) 212 | 213 | 214 | def create_classifier_and_diffusion( 215 | image_size, 216 | classifier_use_fp16, 217 | classifier_width, 218 | classifier_depth, 219 | classifier_attention_resolutions, 220 | classifier_use_scale_shift_norm, 221 | classifier_resblock_updown, 222 | classifier_pool, 223 | learn_sigma, 224 | diffusion_steps, 225 | noise_schedule, 226 | timestep_respacing, 227 | use_kl, 228 | predict_xstart, 229 | rescale_timesteps, 230 | rescale_learned_sigmas, 231 | ): 232 | classifier = create_classifier( 233 | image_size, 234 | classifier_use_fp16, 235 | classifier_width, 236 | classifier_depth, 237 | classifier_attention_resolutions, 238 | classifier_use_scale_shift_norm, 239 | classifier_resblock_updown, 240 | classifier_pool, 241 | ) 242 | diffusion = create_gaussian_diffusion( 243 | steps=diffusion_steps, 244 | learn_sigma=learn_sigma, 245 | noise_schedule=noise_schedule, 246 | use_kl=use_kl, 247 | predict_xstart=predict_xstart, 248 | rescale_timesteps=rescale_timesteps, 249 | rescale_learned_sigmas=rescale_learned_sigmas, 250 | timestep_respacing=timestep_respacing, 251 | ) 252 | return classifier, diffusion 253 | 254 | 255 | def create_classifier( 256 | image_size, 257 | classifier_use_fp16, 258 | classifier_width, 259 | classifier_depth, 260 | classifier_attention_resolutions, 261 | classifier_use_scale_shift_norm, 262 | classifier_resblock_updown, 263 | classifier_pool, 264 | ): 265 | if image_size == 512: 266 | channel_mult = (0.5, 1, 1, 2, 2, 4, 4) 267 | elif image_size == 256: 268 | channel_mult = (1, 1, 2, 2, 4, 4) 269 | elif image_size == 128: 270 | channel_mult = (1, 1, 2, 3, 4) 271 | elif image_size == 64: 272 | channel_mult = (1, 2, 3, 4) 273 | else: 274 | raise ValueError(f"unsupported image size: {image_size}") 275 | 276 | attention_ds = [] 277 | for res in classifier_attention_resolutions.split(","): 278 | attention_ds.append(image_size // int(res)) 279 | 280 | return EncoderUNetModel( 281 | image_size=image_size, 282 | in_channels=3, 283 | model_channels=classifier_width, 284 | out_channels=1000, 285 | num_res_blocks=classifier_depth, 286 | attention_resolutions=tuple(attention_ds), 287 | channel_mult=channel_mult, 288 | use_fp16=classifier_use_fp16, 289 | num_head_channels=64, 290 | use_scale_shift_norm=classifier_use_scale_shift_norm, 291 | resblock_updown=classifier_resblock_updown, 292 | pool=classifier_pool, 293 | ) 294 | 295 | 296 | def sr_model_and_diffusion_defaults(): 297 | res = model_and_diffusion_defaults() 298 | res["large_size"] = 256 299 | res["small_size"] = 64 300 | arg_names = inspect.getfullargspec(sr_create_model_and_diffusion)[0] 301 | for k in res.copy().keys(): 302 | if k not in arg_names: 303 | del res[k] 304 | return res 305 | 306 | 307 | def sr_create_model_and_diffusion( 308 | large_size, 309 | small_size, 310 | class_cond, 311 | learn_sigma, 312 | num_channels, 313 | num_res_blocks, 314 | num_heads, 315 | num_head_channels, 316 | num_heads_upsample, 317 | attention_resolutions, 318 | dropout, 319 | diffusion_steps, 320 | noise_schedule, 321 | timestep_respacing, 322 | use_kl, 323 | predict_xstart, 324 | rescale_timesteps, 325 | rescale_learned_sigmas, 326 | use_checkpoint, 327 | use_scale_shift_norm, 328 | resblock_updown, 329 | use_fp16, 330 | ): 331 | model = sr_create_model( 332 | large_size, 333 | small_size, 334 | num_channels, 335 | num_res_blocks, 336 | learn_sigma=learn_sigma, 337 | class_cond=class_cond, 338 | use_checkpoint=use_checkpoint, 339 | attention_resolutions=attention_resolutions, 340 | num_heads=num_heads, 341 | num_head_channels=num_head_channels, 342 | num_heads_upsample=num_heads_upsample, 343 | use_scale_shift_norm=use_scale_shift_norm, 344 | dropout=dropout, 345 | resblock_updown=resblock_updown, 346 | use_fp16=use_fp16, 347 | ) 348 | diffusion = create_gaussian_diffusion( 349 | steps=diffusion_steps, 350 | learn_sigma=learn_sigma, 351 | noise_schedule=noise_schedule, 352 | use_kl=use_kl, 353 | predict_xstart=predict_xstart, 354 | rescale_timesteps=rescale_timesteps, 355 | rescale_learned_sigmas=rescale_learned_sigmas, 356 | timestep_respacing=timestep_respacing, 357 | ) 358 | return model, diffusion 359 | 360 | 361 | def sr_create_model( 362 | large_size, 363 | small_size, 364 | num_channels, 365 | num_res_blocks, 366 | learn_sigma, 367 | class_cond, 368 | use_checkpoint, 369 | attention_resolutions, 370 | num_heads, 371 | num_head_channels, 372 | num_heads_upsample, 373 | use_scale_shift_norm, 374 | dropout, 375 | resblock_updown, 376 | use_fp16, 377 | ): 378 | _ = small_size # hack to prevent unused variable 379 | 380 | if large_size == 512: 381 | channel_mult = (1, 1, 2, 2, 4, 4) 382 | elif large_size == 256: 383 | channel_mult = (1, 1, 2, 2, 4, 4) 384 | elif large_size == 64: 385 | channel_mult = (1, 2, 3, 4) 386 | elif large_size == 32: 387 | channel_mult = (1, 2, 3, 4) 388 | else: 389 | raise ValueError(f"unsupported large size: {large_size}") 390 | 391 | attention_ds = [] 392 | for res in attention_resolutions.split(","): 393 | attention_ds.append(large_size // int(res)) 394 | 395 | return SuperResModel( 396 | image_size=large_size, 397 | in_channels=3, 398 | model_channels=num_channels, 399 | out_channels=(3 if not learn_sigma else 6), 400 | num_res_blocks=num_res_blocks, 401 | attention_resolutions=tuple(attention_ds), 402 | dropout=dropout, 403 | channel_mult=channel_mult, 404 | num_classes=(NUM_CLASSES if class_cond else None), 405 | use_checkpoint=use_checkpoint, 406 | num_heads=num_heads, 407 | num_head_channels=num_head_channels, 408 | num_heads_upsample=num_heads_upsample, 409 | use_scale_shift_norm=use_scale_shift_norm, 410 | resblock_updown=resblock_updown, 411 | use_fp16=use_fp16, 412 | ) 413 | 414 | 415 | def create_gaussian_diffusion( 416 | *, 417 | steps=1000, 418 | learn_sigma=False, 419 | sigma_small=False, 420 | noise_schedule="linear", 421 | use_kl=False, 422 | predict_xstart=False, 423 | rescale_timesteps=False, 424 | rescale_learned_sigmas=False, 425 | timestep_respacing="", 426 | ): 427 | betas = gd.get_named_beta_schedule(noise_schedule, steps) 428 | if use_kl: 429 | loss_type = gd.LossType.RESCALED_KL 430 | elif rescale_learned_sigmas: 431 | loss_type = gd.LossType.RESCALED_MSE 432 | else: 433 | loss_type = gd.LossType.MSE 434 | if not timestep_respacing: 435 | timestep_respacing = [steps] 436 | return SpacedDiffusion( 437 | use_timesteps=space_timesteps(steps, timestep_respacing), 438 | betas=betas, 439 | model_mean_type=( 440 | gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X 441 | ), 442 | model_var_type=( 443 | ( 444 | gd.ModelVarType.FIXED_LARGE 445 | if not sigma_small 446 | else gd.ModelVarType.FIXED_SMALL 447 | ) 448 | if not learn_sigma 449 | else gd.ModelVarType.LEARNED_RANGE 450 | ), 451 | loss_type=loss_type, 452 | rescale_timesteps=rescale_timesteps, 453 | ) 454 | 455 | 456 | def add_dict_to_argparser(parser, default_dict): 457 | for k, v in default_dict.items(): 458 | v_type = type(v) 459 | if v is None: 460 | v_type = str 461 | elif isinstance(v, bool): 462 | v_type = str2bool 463 | parser.add_argument(f"--{k}", default=v, type=v_type) 464 | 465 | 466 | def args_to_dict(args, keys): 467 | return {k: getattr(args, k) for k in keys} 468 | 469 | 470 | def str2bool(v): 471 | """ 472 | https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse 473 | """ 474 | if isinstance(v, bool): 475 | return v 476 | if v.lower() in ("yes", "true", "t", "y", "1"): 477 | return True 478 | elif v.lower() in ("no", "false", "f", "n", "0"): 479 | return False 480 | else: 481 | raise argparse.ArgumentTypeError("boolean value expected") 482 | -------------------------------------------------------------------------------- /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 | lr_warmup_steps=0 42 | ): 43 | self.model = model 44 | self.diffusion = diffusion 45 | self.data = data 46 | self.batch_size = batch_size 47 | self.microbatch = microbatch if microbatch > 0 else batch_size 48 | self.lr = lr 49 | self.ema_rate = ( 50 | [ema_rate] 51 | if isinstance(ema_rate, float) 52 | else [float(x) for x in ema_rate.split(",")] 53 | ) 54 | self.log_interval = log_interval 55 | self.save_interval = save_interval 56 | self.resume_checkpoint = resume_checkpoint 57 | self.use_fp16 = use_fp16 58 | self.fp16_scale_growth = fp16_scale_growth 59 | self.schedule_sampler = schedule_sampler or UniformSampler(diffusion) 60 | self.weight_decay = weight_decay 61 | self.lr_anneal_steps = lr_anneal_steps 62 | self.lr_warmup_steps = lr_warmup_steps 63 | 64 | self.step = 0 65 | self.resume_step = 0 66 | self.global_batch = self.batch_size * dist.get_world_size() 67 | 68 | self.sync_cuda = th.cuda.is_available() 69 | 70 | self._load_and_sync_parameters() 71 | self.mp_trainer = MixedPrecisionTrainer( 72 | model=self.model, 73 | use_fp16=self.use_fp16, 74 | fp16_scale_growth=fp16_scale_growth, 75 | ) 76 | 77 | self.opt = AdamW( 78 | self.mp_trainer.master_params, lr=self.lr, weight_decay=self.weight_decay 79 | ) 80 | if self.resume_step: 81 | self._load_optimizer_state() 82 | # Model was resumed, either due to a restart or a checkpoint 83 | # being specified at the command line. 84 | self.ema_params = [ 85 | self._load_ema_parameters(rate) for rate in self.ema_rate 86 | ] 87 | else: 88 | self.ema_params = [ 89 | copy.deepcopy(self.mp_trainer.master_params) 90 | for _ in range(len(self.ema_rate)) 91 | ] 92 | 93 | if th.cuda.is_available(): 94 | self.use_ddp = True 95 | self.ddp_model = DDP( 96 | self.model, 97 | device_ids=[dist_util.dev()], 98 | output_device=dist_util.dev(), 99 | broadcast_buffers=False, 100 | bucket_cap_mb=128, 101 | find_unused_parameters=False, 102 | ) 103 | else: 104 | if dist.get_world_size() > 1: 105 | logger.warn( 106 | "Distributed training requires CUDA. " 107 | "Gradients will not be synchronized properly!" 108 | ) 109 | self.use_ddp = False 110 | self.ddp_model = self.model 111 | 112 | def _load_and_sync_parameters(self): 113 | resume_checkpoint = find_resume_checkpoint() or self.resume_checkpoint 114 | 115 | if resume_checkpoint: 116 | self.resume_step = parse_resume_step_from_filename(resume_checkpoint) 117 | if dist.get_rank() == 0: 118 | if self.resume_step == 0: 119 | logger.log(f"loading model for the first time, will ignore missing layers if possible") 120 | state_dict = dist_util.load_state_dict( 121 | resume_checkpoint, map_location=dist_util.dev() 122 | ) 123 | 124 | model_state_dict = self.model.state_dict() 125 | for k in state_dict: 126 | if k in model_state_dict: 127 | if state_dict[k].shape != model_state_dict[k].shape: 128 | logger.info(f"Skip loading parameter: {k}, " 129 | f"required shape: {model_state_dict[k].shape}, " 130 | f"loaded shape: {state_dict[k].shape}") 131 | state_dict[k] = model_state_dict[k] 132 | if k.endswith('weight'): 133 | kb = k.replace('weight','bias') 134 | state_dict[kb] = model_state_dict[kb] 135 | else: 136 | logger.info(f"Dropping parameter {k}") 137 | 138 | self.model.load_state_dict(state_dict, strict=False) 139 | del state_dict 140 | del model_state_dict 141 | th.cuda.empty_cache() 142 | else: 143 | logger.log(f"loading model from checkpoint: {resume_checkpoint}...") 144 | self.model.load_state_dict( 145 | dist_util.load_state_dict( 146 | resume_checkpoint, map_location=dist_util.dev() 147 | ), strict=True 148 | ) 149 | 150 | dist_util.sync_params(self.model.parameters()) 151 | 152 | def _load_ema_parameters(self, rate): 153 | ema_params = copy.deepcopy(self.mp_trainer.master_params) 154 | 155 | main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint 156 | ema_checkpoint = find_ema_checkpoint(main_checkpoint, self.resume_step, rate) 157 | #if ema_checkpoint: 158 | # if dist.get_rank() == 0: 159 | # logger.log(f"loading EMA from checkpoint: {ema_checkpoint}...") 160 | # state_dict = dist_util.load_state_dict( 161 | # ema_checkpoint, map_location=dist_util.dev() 162 | # ) 163 | # ema_params = self.mp_trainer.state_dict_to_master_params(state_dict) 164 | 165 | #dist_util.sync_params(ema_params) 166 | 167 | if ema_checkpoint: 168 | logger.log(f"loading EMA from checkpoint: {ema_checkpoint}...") 169 | state_dict = dist_util.load_state_dict( 170 | ema_checkpoint, map_location=dist_util.dev() 171 | ) 172 | ema_params = self.mp_trainer.state_dict_to_master_params(state_dict) 173 | 174 | return ema_params 175 | 176 | def _load_optimizer_state(self): 177 | main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint 178 | opt_checkpoint = bf.join( 179 | bf.dirname(main_checkpoint), f"opt{self.resume_step:06}.pt" 180 | ) 181 | if bf.exists(opt_checkpoint): 182 | logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}") 183 | state_dict = dist_util.load_state_dict( 184 | opt_checkpoint, map_location=dist_util.dev() 185 | ) 186 | self.opt.load_state_dict(state_dict) 187 | 188 | def run_loop(self): 189 | while ( 190 | not self.lr_anneal_steps 191 | or self.step + self.resume_step < self.lr_anneal_steps 192 | ): 193 | batch, cond = next(self.data) 194 | self.run_step(batch, cond) 195 | if self.step % self.log_interval == 0: 196 | logger.dumpkvs() 197 | if self.step % self.save_interval == 0: 198 | self.save() 199 | # Run for a finite amount of time in integration tests. 200 | if os.environ.get("DIFFUSION_TRAINING_TEST", "") and self.step > 0: 201 | return 202 | self.step += 1 203 | # Save the last checkpoint if it wasn't already saved. 204 | if (self.step - 1) % self.save_interval != 0: 205 | self.save() 206 | 207 | def run_step(self, batch, cond): 208 | self.forward_backward(batch, cond) 209 | took_step = self.mp_trainer.optimize(self.opt) 210 | if took_step: 211 | self._update_ema() 212 | self._warmup_lr() 213 | self._anneal_lr() 214 | self.log_step() 215 | 216 | def forward_backward(self, batch, cond): 217 | self.mp_trainer.zero_grad() 218 | for i in range(0, batch.shape[0], self.microbatch): 219 | micro = batch[i : i + self.microbatch].to(dist_util.dev()) 220 | micro_cond = { 221 | k: v[i : i + self.microbatch].to(dist_util.dev()) 222 | for k, v in cond.items() 223 | } 224 | last_batch = (i + self.microbatch) >= batch.shape[0] 225 | t, weights = self.schedule_sampler.sample(micro.shape[0], dist_util.dev()) 226 | 227 | compute_losses = functools.partial( 228 | self.diffusion.training_losses, 229 | self.ddp_model, 230 | micro, 231 | t, 232 | model_kwargs=micro_cond, 233 | ) 234 | 235 | if last_batch or not self.use_ddp: 236 | losses = compute_losses() 237 | else: 238 | with self.ddp_model.no_sync(): 239 | losses = compute_losses() 240 | 241 | if isinstance(self.schedule_sampler, LossAwareSampler): 242 | self.schedule_sampler.update_with_local_losses( 243 | t, losses["loss"].detach() 244 | ) 245 | 246 | loss = (losses["loss"] * weights).mean() 247 | log_loss_dict( 248 | self.diffusion, t, {k: v * weights for k, v in losses.items()} 249 | ) 250 | self.mp_trainer.backward(loss) 251 | 252 | def _update_ema(self): 253 | for rate, params in zip(self.ema_rate, self.ema_params): 254 | update_ema(params, self.mp_trainer.master_params, rate=rate) 255 | 256 | def _anneal_lr(self): 257 | if not self.lr_anneal_steps: 258 | return 259 | frac_done = (self.step + self.resume_step) / self.lr_anneal_steps 260 | lr = self.lr * (1 - frac_done) 261 | for param_group in self.opt.param_groups: 262 | param_group["lr"] = lr 263 | 264 | def _warmup_lr(self): 265 | if not self.lr_warmup_steps: 266 | return 267 | frac_done = (self.step + self.resume_step) / self.lr_warmup_steps 268 | if frac_done > 1: 269 | return 270 | lr = self.lr * frac_done 271 | 272 | for param_group in self.opt.param_groups: 273 | param_group["lr"] = lr 274 | 275 | logger.log(f"setting lr to {lr}...") 276 | 277 | def log_step(self): 278 | logger.logkv("step", self.step + self.resume_step) 279 | logger.logkv("samples", (self.step + self.resume_step + 1) * self.global_batch) 280 | 281 | def save(self): 282 | def save_checkpoint(rate, params): 283 | state_dict = self.mp_trainer.master_params_to_state_dict(params) 284 | if dist.get_rank() == 0: 285 | logger.log(f"saving model {rate}...") 286 | if not rate: 287 | filename = f"model{(self.step+self.resume_step):06d}.pt" 288 | else: 289 | filename = f"ema_{rate}_{(self.step+self.resume_step):06d}.pt" 290 | with bf.BlobFile(bf.join(get_blob_logdir(), filename), "wb") as f: 291 | th.save(state_dict, f) 292 | 293 | save_checkpoint(0, self.mp_trainer.master_params) 294 | for rate, params in zip(self.ema_rate, self.ema_params): 295 | save_checkpoint(rate, params) 296 | 297 | if dist.get_rank() == 0: 298 | with bf.BlobFile( 299 | bf.join(get_blob_logdir(), f"opt{(self.step+self.resume_step):06d}.pt"), 300 | "wb", 301 | ) as f: 302 | th.save(self.opt.state_dict(), f) 303 | 304 | dist.barrier() 305 | 306 | 307 | def parse_resume_step_from_filename(filename): 308 | """ 309 | Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the 310 | checkpoint's number of steps. 311 | """ 312 | split = filename.split("model") 313 | if len(split) < 2: 314 | return 0 315 | split1 = split[-1].split(".")[0] 316 | try: 317 | return int(split1) 318 | except ValueError: 319 | return 0 320 | 321 | 322 | def get_blob_logdir(): 323 | # You can change this to be a separate path to save checkpoints to 324 | # a blobstore or some external drive. 325 | return logger.get_dir() 326 | 327 | 328 | def find_resume_checkpoint(): 329 | # On your infrastructure, you may want to override this to automatically 330 | # discover the latest checkpoint on your blob storage, etc. 331 | return None 332 | 333 | 334 | def find_ema_checkpoint(main_checkpoint, step, rate): 335 | if main_checkpoint is None: 336 | return None 337 | filename = f"ema_{rate}_{(step):06d}.pt" 338 | path = bf.join(bf.dirname(main_checkpoint), filename) 339 | if bf.exists(path): 340 | return path 341 | return None 342 | 343 | 344 | def log_loss_dict(diffusion, ts, losses): 345 | for key, values in losses.items(): 346 | logger.logkv_mean(key, values.mean().item()) 347 | # Log the quantiles (four quartiles, in particular). 348 | for sub_t, sub_loss in zip(ts.cpu().numpy(), values.detach().cpu().numpy()): 349 | quartile = int(4 * sub_t / diffusion.num_timesteps) 350 | logger.logkv_mean(f"{key}_q{quartile}", sub_loss) 351 | -------------------------------------------------------------------------------- /model-card.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | These are diffusion models and noised image classifiers described in the paper [Diffusion Models Beat GANs on Image Synthesis](https://arxiv.org/abs/2105.05233). 4 | Included in this release are the following models: 5 | 6 | * Noisy ImageNet classifiers at resolutions 64x64, 128x128, 256x256, 512x512 7 | * A class-unconditional ImageNet diffusion model at resolution 256x256 8 | * Class conditional ImageNet diffusion models at 64x64, 128x128, 256x256, 512x512 resolutions 9 | * Class-conditional ImageNet upsampling diffusion models: 64x64->256x256, 128x128->512x512 10 | * Diffusion models trained on three LSUN classes at 256x256 resolution: cat, horse, bedroom 11 | 12 | # Datasets 13 | 14 | All of the models we are releasing were either trained on the [ILSVRC 2012 subset of ImageNet](http://www.image-net.org/challenges/LSVRC/2012/) or on single classes of [LSUN](https://arxiv.org/abs/1506.03365). 15 | Here, we describe characteristics of these datasets which impact model behavior: 16 | 17 | **LSUN**: This dataset was collected in 2015 using a combination of human labeling (from Amazon Mechanical Turk) and automated data labeling. 18 | * Each of the three classes we consider contain over a million images. 19 | * The dataset creators found that the label accuracy was roughly 90% across the entire LSUN dataset when measured by trained experts. 20 | * Images are scraped from the internet, and LSUN cat images in particular tend to often follow a “meme” format. 21 | * We found that there are occasionally humans in these photos, including faces, especially within the cat class. 22 | 23 | **ILSVRC 2012 subset of ImageNet**: This dataset was curated in 2012 and consists of roughly one million images, each belonging to one of 1000 classes. 24 | * A large portion of the classes in this dataset are animals, plants, and other naturally-occurring objects. 25 | * Many images contain humans, although usually these humans aren’t reflected by the class label (e.g. the class “Tench, tinca tinca” contains many photos of people holding fish). 26 | 27 | # Performance 28 | 29 | These models are intended to generate samples consistent with their training distributions. 30 | This has been measured in terms of FID, Precision, and Recall. 31 | These metrics all rely on the representations of a [pre-trained Inception-V3 model](https://arxiv.org/abs/1512.00567), 32 | which was trained on ImageNet, and so is likely to focus more on the ImageNet classes (such as animals) than on other visual features (such as human faces). 33 | 34 | Qualitatively, the samples produced by these models often look highly realistic, especially when a diffusion model is combined with a noisy classifier. 35 | 36 | # Intended Use 37 | 38 | These models are intended to be used for research purposes only. 39 | In particular, they can be used as a baseline for generative modeling research, or as a starting point to build off of for such research. 40 | 41 | These models are not intended to be commercially deployed. 42 | Additionally, they are not intended to be used to create propaganda or offensive imagery. 43 | 44 | Before releasing these models, we probed their ability to ease the creation of targeted imagery, since doing so could be potentially harmful. 45 | We did this either by fine-tuning our ImageNet models on a target LSUN class, or through classifier guidance with publicly available [CLIP models](https://github.com/openai/CLIP). 46 | * To probe fine-tuning capabilities, we restricted our compute budget to roughly $100 and tried both standard fine-tuning, 47 | and a diffusion-specific approach where we train a specialized classifier for the LSUN class. The resulting FIDs were significantly worse than publicly available GAN models, indicating that fine-tuning an ImageNet diffusion model does not significantly lower the cost of image generation. 48 | * To probe guidance with CLIP, we tried two approaches for using pre-trained CLIP models for classifier guidance. Either we fed the noised image to CLIP directly and used its gradients, or we fed the diffusion model's denoised prediction to the CLIP model and differentiated through the whole process. In both cases, we found that it was difficult to recover information from the CLIP model, indicating that these diffusion models are unlikely to make it significantly easier to extract knowledge from CLIP compared to existing GAN models. 49 | 50 | # Limitations 51 | 52 | These models sometimes produce highly unrealistic outputs, particularly when generating images containing human faces. 53 | This may stem from ImageNet's emphasis on non-human objects. 54 | 55 | While classifier guidance can improve sample quality, it reduces diversity, resulting in some modes of the data distribution being underrepresented. 56 | This can potentially amplify existing biases in the training dataset such as gender and racial biases. 57 | 58 | Because ImageNet and LSUN contain images from the internet, they include photos of real people, and the model may have memorized some of the information contained in these photos. 59 | However, these images are already publicly available, and existing generative models trained on ImageNet have not demonstrated significant leakage of this information. -------------------------------------------------------------------------------- /scripts/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 | 14 | from guided_diffusion import dist_util, logger 15 | from guided_diffusion.script_util import ( 16 | NUM_CLASSES, 17 | model_and_diffusion_defaults, 18 | classifier_defaults, 19 | create_model_and_diffusion, 20 | create_classifier, 21 | add_dict_to_argparser, 22 | args_to_dict, 23 | ) 24 | 25 | 26 | def main(): 27 | args = create_argparser().parse_args() 28 | 29 | dist_util.setup_dist() 30 | logger.configure() 31 | 32 | logger.log("creating model and diffusion...") 33 | model, diffusion = create_model_and_diffusion( 34 | **args_to_dict(args, model_and_diffusion_defaults().keys()) 35 | ) 36 | model.load_state_dict( 37 | dist_util.load_state_dict(args.model_path, map_location="cpu") 38 | ) 39 | model.to(dist_util.dev()) 40 | if args.use_fp16: 41 | model.convert_to_fp16() 42 | model.eval() 43 | 44 | logger.log("loading classifier...") 45 | classifier = create_classifier(**args_to_dict(args, classifier_defaults().keys())) 46 | classifier.load_state_dict( 47 | dist_util.load_state_dict(args.classifier_path, map_location="cpu") 48 | ) 49 | classifier.to(dist_util.dev()) 50 | if args.classifier_use_fp16: 51 | classifier.convert_to_fp16() 52 | classifier.eval() 53 | 54 | def cond_fn(x, t, y=None): 55 | assert y is not None 56 | with th.enable_grad(): 57 | x_in = x.detach().requires_grad_(True) 58 | logits = classifier(x_in, t) 59 | log_probs = F.log_softmax(logits, dim=-1) 60 | selected = log_probs[range(len(logits)), y.view(-1)] 61 | return th.autograd.grad(selected.sum(), x_in)[0] * args.classifier_scale 62 | 63 | def model_fn(x, t, y=None): 64 | assert y is not None 65 | return model(x, t, y if args.class_cond else None) 66 | 67 | logger.log("sampling...") 68 | all_images = [] 69 | all_labels = [] 70 | while len(all_images) * args.batch_size < args.num_samples: 71 | model_kwargs = {} 72 | classes = th.randint( 73 | low=0, high=NUM_CLASSES, size=(args.batch_size,), device=dist_util.dev() 74 | ) 75 | model_kwargs["y"] = classes 76 | sample_fn = ( 77 | diffusion.p_sample_loop if not args.use_ddim else diffusion.ddim_sample_loop 78 | ) 79 | sample = sample_fn( 80 | model_fn, 81 | (args.batch_size, 3, args.image_size, args.image_size), 82 | clip_denoised=args.clip_denoised, 83 | model_kwargs=model_kwargs, 84 | cond_fn=cond_fn, 85 | device=dist_util.dev(), 86 | ) 87 | sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8) 88 | sample = sample.permute(0, 2, 3, 1) 89 | sample = sample.contiguous() 90 | 91 | gathered_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())] 92 | dist.all_gather(gathered_samples, sample) # gather not supported with NCCL 93 | all_images.extend([sample.cpu().numpy() for sample in gathered_samples]) 94 | gathered_labels = [th.zeros_like(classes) for _ in range(dist.get_world_size())] 95 | dist.all_gather(gathered_labels, classes) 96 | all_labels.extend([labels.cpu().numpy() for labels in gathered_labels]) 97 | logger.log(f"created {len(all_images) * args.batch_size} samples") 98 | 99 | arr = np.concatenate(all_images, axis=0) 100 | arr = arr[: args.num_samples] 101 | label_arr = np.concatenate(all_labels, axis=0) 102 | label_arr = label_arr[: args.num_samples] 103 | if dist.get_rank() == 0: 104 | shape_str = "x".join([str(x) for x in arr.shape]) 105 | out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz") 106 | logger.log(f"saving to {out_path}") 107 | np.savez(out_path, arr, label_arr) 108 | 109 | dist.barrier() 110 | logger.log("sampling complete") 111 | 112 | 113 | def create_argparser(): 114 | defaults = dict( 115 | clip_denoised=True, 116 | num_samples=10000, 117 | batch_size=16, 118 | use_ddim=False, 119 | model_path="", 120 | classifier_path="", 121 | classifier_scale=1.0, 122 | ) 123 | defaults.update(model_and_diffusion_defaults()) 124 | defaults.update(classifier_defaults()) 125 | parser = argparse.ArgumentParser() 126 | add_dict_to_argparser(parser, defaults) 127 | return parser 128 | 129 | 130 | if __name__ == "__main__": 131 | main() 132 | -------------------------------------------------------------------------------- /scripts/classifier_train.py: -------------------------------------------------------------------------------- 1 | """ 2 | Train a noised image classifier on ImageNet. 3 | """ 4 | 5 | import argparse 6 | import os 7 | 8 | import blobfile as bf 9 | import torch as th 10 | import torch.distributed as dist 11 | import torch.nn.functional as F 12 | from torch.nn.parallel.distributed import DistributedDataParallel as DDP 13 | from torch.optim import AdamW 14 | 15 | from guided_diffusion import dist_util, logger 16 | from guided_diffusion.fp16_util import MixedPrecisionTrainer 17 | from guided_diffusion.image_datasets import load_data 18 | from guided_diffusion.resample import create_named_schedule_sampler 19 | from guided_diffusion.script_util import ( 20 | add_dict_to_argparser, 21 | args_to_dict, 22 | classifier_and_diffusion_defaults, 23 | create_classifier_and_diffusion, 24 | ) 25 | from guided_diffusion.train_util import parse_resume_step_from_filename, log_loss_dict 26 | 27 | 28 | def main(): 29 | args = create_argparser().parse_args() 30 | 31 | dist_util.setup_dist() 32 | logger.configure() 33 | 34 | logger.log("creating model and diffusion...") 35 | model, diffusion = create_classifier_and_diffusion( 36 | **args_to_dict(args, classifier_and_diffusion_defaults().keys()) 37 | ) 38 | model.to(dist_util.dev()) 39 | if args.noised: 40 | schedule_sampler = create_named_schedule_sampler( 41 | args.schedule_sampler, diffusion 42 | ) 43 | 44 | resume_step = 0 45 | if args.resume_checkpoint: 46 | resume_step = parse_resume_step_from_filename(args.resume_checkpoint) 47 | if dist.get_rank() == 0: 48 | logger.log( 49 | f"loading model from checkpoint: {args.resume_checkpoint}... at {resume_step} step" 50 | ) 51 | model.load_state_dict( 52 | dist_util.load_state_dict( 53 | args.resume_checkpoint, map_location=dist_util.dev() 54 | ) 55 | ) 56 | 57 | # Needed for creating correct EMAs and fp16 parameters. 58 | dist_util.sync_params(model.parameters()) 59 | 60 | mp_trainer = MixedPrecisionTrainer( 61 | model=model, use_fp16=args.classifier_use_fp16, initial_lg_loss_scale=16.0 62 | ) 63 | 64 | model = DDP( 65 | model, 66 | device_ids=[dist_util.dev()], 67 | output_device=dist_util.dev(), 68 | broadcast_buffers=False, 69 | bucket_cap_mb=128, 70 | find_unused_parameters=False, 71 | ) 72 | 73 | logger.log("creating data loader...") 74 | data = load_data( 75 | data_dir=args.data_dir, 76 | batch_size=args.batch_size, 77 | image_size=args.image_size, 78 | class_cond=True, 79 | random_crop=True, 80 | ) 81 | if args.val_data_dir: 82 | val_data = load_data( 83 | data_dir=args.val_data_dir, 84 | batch_size=args.batch_size, 85 | image_size=args.image_size, 86 | class_cond=True, 87 | ) 88 | else: 89 | val_data = None 90 | 91 | logger.log(f"creating optimizer...") 92 | opt = AdamW(mp_trainer.master_params, lr=args.lr, weight_decay=args.weight_decay) 93 | if args.resume_checkpoint: 94 | opt_checkpoint = bf.join( 95 | bf.dirname(args.resume_checkpoint), f"opt{resume_step:06}.pt" 96 | ) 97 | logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}") 98 | opt.load_state_dict( 99 | dist_util.load_state_dict(opt_checkpoint, map_location=dist_util.dev()) 100 | ) 101 | 102 | logger.log("training classifier model...") 103 | 104 | def forward_backward_log(data_loader, prefix="train"): 105 | batch, extra = next(data_loader) 106 | labels = extra["y"].to(dist_util.dev()) 107 | 108 | batch = batch.to(dist_util.dev()) 109 | # Noisy images 110 | if args.noised: 111 | t, _ = schedule_sampler.sample(batch.shape[0], dist_util.dev()) 112 | batch = diffusion.q_sample(batch, t) 113 | else: 114 | t = th.zeros(batch.shape[0], dtype=th.long, device=dist_util.dev()) 115 | 116 | for i, (sub_batch, sub_labels, sub_t) in enumerate( 117 | split_microbatches(args.microbatch, batch, labels, t) 118 | ): 119 | logits = model(sub_batch, timesteps=sub_t) 120 | loss = F.cross_entropy(logits, sub_labels, reduction="none") 121 | 122 | losses = {} 123 | losses[f"{prefix}_loss"] = loss.detach() 124 | losses[f"{prefix}_acc@1"] = compute_top_k( 125 | logits, sub_labels, k=1, reduction="none" 126 | ) 127 | losses[f"{prefix}_acc@5"] = compute_top_k( 128 | logits, sub_labels, k=5, reduction="none" 129 | ) 130 | log_loss_dict(diffusion, sub_t, losses) 131 | del losses 132 | loss = loss.mean() 133 | if loss.requires_grad: 134 | if i == 0: 135 | mp_trainer.zero_grad() 136 | mp_trainer.backward(loss * len(sub_batch) / len(batch)) 137 | 138 | for step in range(args.iterations - resume_step): 139 | logger.logkv("step", step + resume_step) 140 | logger.logkv( 141 | "samples", 142 | (step + resume_step + 1) * args.batch_size * dist.get_world_size(), 143 | ) 144 | if args.anneal_lr: 145 | set_annealed_lr(opt, args.lr, (step + resume_step) / args.iterations) 146 | forward_backward_log(data) 147 | mp_trainer.optimize(opt) 148 | if val_data is not None and not step % args.eval_interval: 149 | with th.no_grad(): 150 | with model.no_sync(): 151 | model.eval() 152 | forward_backward_log(val_data, prefix="val") 153 | model.train() 154 | if not step % args.log_interval: 155 | logger.dumpkvs() 156 | if ( 157 | step 158 | and dist.get_rank() == 0 159 | and not (step + resume_step) % args.save_interval 160 | ): 161 | logger.log("saving model...") 162 | save_model(mp_trainer, opt, step + resume_step) 163 | 164 | if dist.get_rank() == 0: 165 | logger.log("saving model...") 166 | save_model(mp_trainer, opt, step + resume_step) 167 | dist.barrier() 168 | 169 | 170 | def set_annealed_lr(opt, base_lr, frac_done): 171 | lr = base_lr * (1 - frac_done) 172 | for param_group in opt.param_groups: 173 | param_group["lr"] = lr 174 | 175 | 176 | def save_model(mp_trainer, opt, step): 177 | if dist.get_rank() == 0: 178 | th.save( 179 | mp_trainer.master_params_to_state_dict(mp_trainer.master_params), 180 | os.path.join(logger.get_dir(), f"model{step:06d}.pt"), 181 | ) 182 | th.save(opt.state_dict(), os.path.join(logger.get_dir(), f"opt{step:06d}.pt")) 183 | 184 | 185 | def compute_top_k(logits, labels, k, reduction="mean"): 186 | _, top_ks = th.topk(logits, k, dim=-1) 187 | if reduction == "mean": 188 | return (top_ks == labels[:, None]).float().sum(dim=-1).mean().item() 189 | elif reduction == "none": 190 | return (top_ks == labels[:, None]).float().sum(dim=-1) 191 | 192 | 193 | def split_microbatches(microbatch, *args): 194 | bs = len(args[0]) 195 | if microbatch == -1 or microbatch >= bs: 196 | yield tuple(args) 197 | else: 198 | for i in range(0, bs, microbatch): 199 | yield tuple(x[i : i + microbatch] if x is not None else None for x in args) 200 | 201 | 202 | def create_argparser(): 203 | defaults = dict( 204 | data_dir="", 205 | val_data_dir="", 206 | noised=True, 207 | iterations=150000, 208 | lr=3e-4, 209 | weight_decay=0.0, 210 | anneal_lr=False, 211 | batch_size=4, 212 | microbatch=-1, 213 | schedule_sampler="uniform", 214 | resume_checkpoint="", 215 | log_interval=10, 216 | eval_interval=5, 217 | save_interval=10000, 218 | ) 219 | defaults.update(classifier_and_diffusion_defaults()) 220 | parser = argparse.ArgumentParser() 221 | add_dict_to_argparser(parser, defaults) 222 | return parser 223 | 224 | 225 | if __name__ == "__main__": 226 | main() 227 | -------------------------------------------------------------------------------- /scripts/image_nll.py: -------------------------------------------------------------------------------- 1 | """ 2 | Approximate the bits/dimension for an image model. 3 | """ 4 | 5 | import argparse 6 | import os 7 | 8 | import numpy as np 9 | import torch.distributed as dist 10 | 11 | from guided_diffusion import dist_util, logger 12 | from guided_diffusion.image_datasets import load_data 13 | from guided_diffusion.script_util import ( 14 | model_and_diffusion_defaults, 15 | create_model_and_diffusion, 16 | add_dict_to_argparser, 17 | args_to_dict, 18 | ) 19 | 20 | 21 | def main(): 22 | args = create_argparser().parse_args() 23 | 24 | dist_util.setup_dist() 25 | logger.configure() 26 | 27 | logger.log("creating model and diffusion...") 28 | model, diffusion = create_model_and_diffusion( 29 | **args_to_dict(args, model_and_diffusion_defaults().keys()) 30 | ) 31 | model.load_state_dict( 32 | dist_util.load_state_dict(args.model_path, map_location="cpu") 33 | ) 34 | model.to(dist_util.dev()) 35 | model.eval() 36 | 37 | logger.log("creating data loader...") 38 | data = load_data( 39 | data_dir=args.data_dir, 40 | batch_size=args.batch_size, 41 | image_size=args.image_size, 42 | class_cond=args.class_cond, 43 | deterministic=True, 44 | ) 45 | 46 | logger.log("evaluating...") 47 | run_bpd_evaluation(model, diffusion, data, args.num_samples, args.clip_denoised) 48 | 49 | 50 | def run_bpd_evaluation(model, diffusion, data, num_samples, clip_denoised): 51 | all_bpd = [] 52 | all_metrics = {"vb": [], "mse": [], "xstart_mse": []} 53 | num_complete = 0 54 | while num_complete < num_samples: 55 | batch, model_kwargs = next(data) 56 | batch = batch.to(dist_util.dev()) 57 | model_kwargs = {k: v.to(dist_util.dev()) for k, v in model_kwargs.items()} 58 | minibatch_metrics = diffusion.calc_bpd_loop( 59 | model, batch, clip_denoised=clip_denoised, model_kwargs=model_kwargs 60 | ) 61 | 62 | for key, term_list in all_metrics.items(): 63 | terms = minibatch_metrics[key].mean(dim=0) / dist.get_world_size() 64 | dist.all_reduce(terms) 65 | term_list.append(terms.detach().cpu().numpy()) 66 | 67 | total_bpd = minibatch_metrics["total_bpd"] 68 | total_bpd = total_bpd.mean() / dist.get_world_size() 69 | dist.all_reduce(total_bpd) 70 | all_bpd.append(total_bpd.item()) 71 | num_complete += dist.get_world_size() * batch.shape[0] 72 | 73 | logger.log(f"done {num_complete} samples: bpd={np.mean(all_bpd)}") 74 | 75 | if dist.get_rank() == 0: 76 | for name, terms in all_metrics.items(): 77 | out_path = os.path.join(logger.get_dir(), f"{name}_terms.npz") 78 | logger.log(f"saving {name} terms to {out_path}") 79 | np.savez(out_path, np.mean(np.stack(terms), axis=0)) 80 | 81 | dist.barrier() 82 | logger.log("evaluation complete") 83 | 84 | 85 | def create_argparser(): 86 | defaults = dict( 87 | data_dir="", clip_denoised=True, num_samples=1000, batch_size=1, model_path="" 88 | ) 89 | defaults.update(model_and_diffusion_defaults()) 90 | parser = argparse.ArgumentParser() 91 | add_dict_to_argparser(parser, defaults) 92 | return parser 93 | 94 | 95 | if __name__ == "__main__": 96 | main() 97 | -------------------------------------------------------------------------------- /scripts/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 | 13 | from guided_diffusion import dist_util, logger 14 | from guided_diffusion.script_util import ( 15 | NUM_CLASSES, 16 | model_and_diffusion_defaults, 17 | create_model_and_diffusion, 18 | add_dict_to_argparser, 19 | args_to_dict, 20 | ) 21 | 22 | 23 | def main(): 24 | args = create_argparser().parse_args() 25 | 26 | dist_util.setup_dist() 27 | logger.configure() 28 | 29 | logger.log("creating model and diffusion...") 30 | model, diffusion = create_model_and_diffusion( 31 | **args_to_dict(args, model_and_diffusion_defaults().keys()) 32 | ) 33 | model.load_state_dict( 34 | dist_util.load_state_dict(args.model_path, map_location="cpu") 35 | ) 36 | model.to(dist_util.dev()) 37 | if args.use_fp16: 38 | model.convert_to_fp16() 39 | model.eval() 40 | 41 | logger.log("sampling...") 42 | all_images = [] 43 | all_labels = [] 44 | while len(all_images) * args.batch_size < args.num_samples: 45 | model_kwargs = {} 46 | if args.class_cond: 47 | classes = th.randint( 48 | low=0, high=NUM_CLASSES, size=(args.batch_size,), device=dist_util.dev() 49 | ) 50 | model_kwargs["y"] = classes 51 | sample_fn = ( 52 | diffusion.p_sample_loop if not args.use_ddim else diffusion.ddim_sample_loop 53 | ) 54 | sample = sample_fn( 55 | model, 56 | (args.batch_size, 3, args.image_size, args.image_size), 57 | clip_denoised=args.clip_denoised, 58 | model_kwargs=model_kwargs, 59 | ) 60 | sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8) 61 | sample = sample.permute(0, 2, 3, 1) 62 | sample = sample.contiguous() 63 | 64 | gathered_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())] 65 | dist.all_gather(gathered_samples, sample) # gather not supported with NCCL 66 | all_images.extend([sample.cpu().numpy() for sample in gathered_samples]) 67 | if args.class_cond: 68 | gathered_labels = [ 69 | th.zeros_like(classes) for _ in range(dist.get_world_size()) 70 | ] 71 | dist.all_gather(gathered_labels, classes) 72 | all_labels.extend([labels.cpu().numpy() for labels in gathered_labels]) 73 | logger.log(f"created {len(all_images) * args.batch_size} samples") 74 | 75 | arr = np.concatenate(all_images, axis=0) 76 | arr = arr[: args.num_samples] 77 | if args.class_cond: 78 | label_arr = np.concatenate(all_labels, axis=0) 79 | label_arr = label_arr[: args.num_samples] 80 | if dist.get_rank() == 0: 81 | shape_str = "x".join([str(x) for x in arr.shape]) 82 | out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz") 83 | logger.log(f"saving to {out_path}") 84 | if args.class_cond: 85 | np.savez(out_path, arr, label_arr) 86 | else: 87 | np.savez(out_path, arr) 88 | 89 | dist.barrier() 90 | logger.log("sampling complete") 91 | 92 | 93 | def create_argparser(): 94 | defaults = dict( 95 | clip_denoised=True, 96 | num_samples=10000, 97 | batch_size=16, 98 | use_ddim=False, 99 | model_path="", 100 | ) 101 | defaults.update(model_and_diffusion_defaults()) 102 | parser = argparse.ArgumentParser() 103 | add_dict_to_argparser(parser, defaults) 104 | return parser 105 | 106 | 107 | if __name__ == "__main__": 108 | main() 109 | -------------------------------------------------------------------------------- /scripts/image_train.py: -------------------------------------------------------------------------------- 1 | """ 2 | Train a diffusion model on images. 3 | """ 4 | 5 | import argparse 6 | 7 | from guided_diffusion import dist_util, logger 8 | from guided_diffusion.image_datasets import load_data 9 | from guided_diffusion.resample import create_named_schedule_sampler 10 | from guided_diffusion.script_util import ( 11 | model_and_diffusion_defaults, 12 | create_model_and_diffusion, 13 | args_to_dict, 14 | add_dict_to_argparser, 15 | ) 16 | from guided_diffusion.train_util import TrainLoop 17 | 18 | 19 | def main(): 20 | args = create_argparser().parse_args() 21 | 22 | dist_util.setup_dist() 23 | logger.configure() 24 | 25 | logger.log("creating model and diffusion...") 26 | model, diffusion = create_model_and_diffusion( 27 | **args_to_dict(args, model_and_diffusion_defaults().keys()) 28 | ) 29 | model.to(dist_util.dev()) 30 | schedule_sampler = create_named_schedule_sampler(args.schedule_sampler, diffusion) 31 | 32 | logger.log("creating data loader...") 33 | data = load_data( 34 | data_dir=args.data_dir, 35 | batch_size=args.batch_size, 36 | image_size=args.image_size, 37 | class_cond=args.class_cond, 38 | ) 39 | logger.log("training...") 40 | TrainLoop( 41 | model=model, 42 | diffusion=diffusion, 43 | data=data, 44 | batch_size=args.batch_size, 45 | microbatch=args.microbatch, 46 | lr=args.lr, 47 | ema_rate=args.ema_rate, 48 | log_interval=args.log_interval, 49 | save_interval=args.save_interval, 50 | resume_checkpoint=args.resume_checkpoint, 51 | use_fp16=args.use_fp16, 52 | fp16_scale_growth=args.fp16_scale_growth, 53 | schedule_sampler=schedule_sampler, 54 | weight_decay=args.weight_decay, 55 | lr_anneal_steps=args.lr_anneal_steps, 56 | ).run_loop() 57 | 58 | 59 | def create_argparser(): 60 | defaults = dict( 61 | data_dir="", 62 | schedule_sampler="uniform", 63 | lr=1e-4, 64 | weight_decay=0.0, 65 | lr_anneal_steps=0, 66 | batch_size=1, 67 | microbatch=-1, # -1 disables microbatches 68 | ema_rate="0.9999", # comma-separated list of EMA values 69 | log_interval=10, 70 | save_interval=10000, 71 | resume_checkpoint="", 72 | use_fp16=False, 73 | fp16_scale_growth=1e-3, 74 | ) 75 | defaults.update(model_and_diffusion_defaults()) 76 | parser = argparse.ArgumentParser() 77 | add_dict_to_argparser(parser, defaults) 78 | return parser 79 | 80 | 81 | if __name__ == "__main__": 82 | main() 83 | -------------------------------------------------------------------------------- /scripts/image_train_inpaint.py: -------------------------------------------------------------------------------- 1 | """ 2 | Train a diffusion model on images. 3 | """ 4 | 5 | import argparse 6 | 7 | from guided_diffusion import dist_util, logger 8 | from guided_diffusion.image_text_datasets import load_data 9 | from guided_diffusion.resample import create_named_schedule_sampler 10 | from guided_diffusion.script_util import ( 11 | model_and_diffusion_defaults, 12 | create_model_and_diffusion, 13 | args_to_dict, 14 | add_dict_to_argparser, 15 | ) 16 | from guided_diffusion.train_util import TrainLoop 17 | import torch 18 | import random 19 | 20 | from encoders.modules import BERTEmbedder 21 | 22 | def set_requires_grad(model, value): 23 | for param in model.parameters(): 24 | param.requires_grad = value 25 | 26 | def main(): 27 | args = create_argparser().parse_args() 28 | 29 | dist_util.setup_dist() 30 | logger.configure() 31 | 32 | from clip_custom import clip # make clip end up on the right device 33 | 34 | logger.log("loading clip...") 35 | clip_model, _ = clip.load('ViT-L/14', device=dist_util.dev(), jit=False) 36 | clip_model.eval().requires_grad_(False) 37 | set_requires_grad(clip_model, False) 38 | 39 | del clip_model.visual 40 | 41 | logger.log("loading vae...") 42 | 43 | encoder = torch.load(args.kl_model, map_location="cpu") 44 | encoder.half().to(dist_util.dev()) 45 | encoder.eval() 46 | set_requires_grad(encoder, False) 47 | 48 | del encoder.decoder 49 | del encoder.loss 50 | 51 | logger.log("loading text encoder...") 52 | 53 | 54 | bert = BERTEmbedder(1280, 32) 55 | sd = torch.load(args.bert_model, map_location="cpu") 56 | bert.load_state_dict(sd) 57 | 58 | bert.half().to(dist_util.dev()) 59 | bert.eval() 60 | set_requires_grad(bert, False) 61 | 62 | logger.log("creating model and diffusion...") 63 | model, diffusion = create_model_and_diffusion( 64 | **args_to_dict(args, model_and_diffusion_defaults().keys()) 65 | ) 66 | 67 | model.to(dist_util.dev()) 68 | 69 | logger.log('total base parameters', sum(x.numel() for x in model.parameters())) 70 | 71 | schedule_sampler = create_named_schedule_sampler(args.schedule_sampler, diffusion) 72 | 73 | logger.log("creating data loader...") 74 | data = load_latent_data( 75 | encoder, 76 | bert, 77 | clip_model, 78 | clip, 79 | data_dir=args.data_dir, 80 | batch_size=args.batch_size, 81 | image_size=args.image_size, 82 | ) 83 | logger.log("training...") 84 | TrainLoop( 85 | model=model, 86 | diffusion=diffusion, 87 | data=data, 88 | batch_size=args.batch_size, 89 | microbatch=args.microbatch, 90 | lr=args.lr, 91 | ema_rate=args.ema_rate, 92 | log_interval=args.log_interval, 93 | save_interval=args.save_interval, 94 | resume_checkpoint=args.resume_checkpoint, 95 | use_fp16=args.use_fp16, 96 | fp16_scale_growth=args.fp16_scale_growth, 97 | schedule_sampler=schedule_sampler, 98 | weight_decay=args.weight_decay, 99 | lr_anneal_steps=args.lr_anneal_steps, 100 | ).run_loop() 101 | 102 | def load_latent_data(encoder, bert, clip_model, clip, data_dir, batch_size, image_size): 103 | data = load_data( 104 | data_dir=data_dir, 105 | batch_size=batch_size, 106 | image_size=256, 107 | class_cond=False, 108 | ) 109 | 110 | blur = transforms.GaussianBlur(kernel_size=(15, 15), sigma=(0.1, 5)) 111 | 112 | for batch, model_kwargs, text in data: 113 | 114 | text = list(text) 115 | for i in range(len(text)): 116 | if random.randint(0,100) < 20: 117 | text[i] = '' 118 | 119 | text_emb = bert.encode(text).to(dist_util.dev()).half() 120 | 121 | clip_text = clip.tokenize(text, truncate=True).to(dist_util.dev()) 122 | clip_emb = clip_model.encode_text(clip_text) 123 | 124 | model_kwargs["context"] = text_emb 125 | model_kwargs["clip_embed"] = clip_emb 126 | 127 | batch = batch.to(dist_util.dev()) 128 | emb = encoder.encode(batch.half()).sample().half() 129 | emb *= 0.18215 130 | 131 | emb_cond = emb.detach().clone() 132 | 133 | for i in range(batch.shape[0]): 134 | if random.randint(0,100) < 20: 135 | emb_cond[i,:,:,:] = 0 # unconditional 136 | else: 137 | if random.randint(0,100) < 50: 138 | mask = torch.randn(1, 32, 32) 139 | mask = blur(mask) 140 | mask = (mask > 0) 141 | mask = mask.repeat(4, 1, 1) 142 | mask = mask.float() 143 | emb_cond[i] *= mask 144 | else: 145 | # mask out 4 random rectangles 146 | for j in range(random.randint(1,4)): 147 | max_area = 32*16 148 | w = random.randint(1,32) 149 | h = random.randint(1,32) 150 | if w*h > max_area: 151 | if random.randint(0,100) < 50: 152 | w = max_area//h 153 | else: 154 | h = max_area//w 155 | if w == 32: 156 | offsetx = 0 157 | else: 158 | offsetx = random.randint(0, 32-w) 159 | if h == 32: 160 | offsety = 0 161 | else: 162 | offsety = random.randint(0, 32-h) 163 | emb_cond[i,:, offsety:offsety+h, offsetx:offsetx+w] = 0 164 | 165 | model_kwargs["image_embed"] = emb_cond 166 | 167 | yield emb, model_kwargs 168 | 169 | def create_argparser(): 170 | defaults = dict( 171 | data_dir="", 172 | schedule_sampler="uniform", 173 | lr=1e-4, 174 | weight_decay=0.0, 175 | lr_anneal_steps=0, 176 | batch_size=1, 177 | microbatch=-1, # -1 disables microbatches 178 | ema_rate="0.9999", # comma-separated list of EMA values 179 | log_interval=10, 180 | save_interval=10000, 181 | resume_checkpoint="", 182 | use_fp16=False, 183 | fp16_scale_growth=1e-3, 184 | kl_model=None, 185 | bert_model=None, 186 | ) 187 | defaults.update(model_and_diffusion_defaults()) 188 | 189 | defaults['clip_embed_dim'] = 768 190 | defaults['image_condition'] = True 191 | 192 | parser = argparse.ArgumentParser() 193 | add_dict_to_argparser(parser, defaults) 194 | return parser 195 | 196 | 197 | if __name__ == "__main__": 198 | main() 199 | -------------------------------------------------------------------------------- /scripts/image_train_latent.py: -------------------------------------------------------------------------------- 1 | """ 2 | Train a diffusion model on images. 3 | """ 4 | 5 | import argparse 6 | 7 | from guided_diffusion import dist_util, logger 8 | from guided_diffusion.image_text_datasets import load_data 9 | from guided_diffusion.resample import create_named_schedule_sampler 10 | from guided_diffusion.script_util import ( 11 | model_and_diffusion_defaults, 12 | create_model_and_diffusion, 13 | args_to_dict, 14 | add_dict_to_argparser, 15 | ) 16 | from guided_diffusion.train_util import TrainLoop 17 | import torch 18 | import random 19 | 20 | from encoders.modules import BERTEmbedder 21 | 22 | def set_requires_grad(model, value): 23 | for param in model.parameters(): 24 | param.requires_grad = value 25 | 26 | def main(): 27 | args = create_argparser().parse_args() 28 | 29 | dist_util.setup_dist() 30 | logger.configure() 31 | 32 | logger.log("loading vae...") 33 | 34 | encoder = torch.load(args.kl_model, map_location="cpu") 35 | encoder.to(dist_util.dev()) 36 | encoder.eval() 37 | set_requires_grad(encoder, False) 38 | 39 | del encoder.decoder 40 | del encoder.loss 41 | 42 | logger.log("loading text encoder...") 43 | 44 | 45 | bert = BERTEmbedder(1280, 32) 46 | sd = torch.load(args.bert_model, map_location="cpu") 47 | bert.load_state_dict(sd) 48 | 49 | bert.to(dist_util.dev()) 50 | bert.eval() 51 | set_requires_grad(bert, False) 52 | 53 | logger.log("creating model and diffusion...") 54 | model, diffusion = create_model_and_diffusion( 55 | **args_to_dict(args, model_and_diffusion_defaults().keys()) 56 | ) 57 | 58 | model.to(dist_util.dev()) 59 | 60 | logger.log('total base parameters', sum(x.numel() for x in model.parameters())) 61 | 62 | schedule_sampler = create_named_schedule_sampler(args.schedule_sampler, diffusion) 63 | 64 | logger.log("creating data loader...") 65 | data = load_latent_data( 66 | encoder, 67 | bert, 68 | data_dir=args.data_dir, 69 | batch_size=args.batch_size, 70 | image_size=args.image_size, 71 | ) 72 | logger.log("training...") 73 | TrainLoop( 74 | model=model, 75 | diffusion=diffusion, 76 | data=data, 77 | batch_size=args.batch_size, 78 | microbatch=args.microbatch, 79 | lr=args.lr, 80 | ema_rate=args.ema_rate, 81 | log_interval=args.log_interval, 82 | save_interval=args.save_interval, 83 | resume_checkpoint=args.resume_checkpoint, 84 | use_fp16=args.use_fp16, 85 | fp16_scale_growth=args.fp16_scale_growth, 86 | schedule_sampler=schedule_sampler, 87 | weight_decay=args.weight_decay, 88 | lr_anneal_steps=args.lr_anneal_steps, 89 | ).run_loop() 90 | 91 | def load_latent_data(encoder, bert, data_dir, batch_size, image_size): 92 | data = load_data( 93 | data_dir=data_dir, 94 | batch_size=batch_size, 95 | image_size=256, 96 | class_cond=False, 97 | ) 98 | for batch, model_kwargs, text in data: 99 | 100 | text = list(text) 101 | for i in range(len(text)): 102 | if random.randint(0,100) < 20: 103 | text[i] = '' 104 | 105 | text_emb = bert.encode(text).to(dist_util.dev()).half() 106 | 107 | model_kwargs["context"] = text_emb 108 | 109 | batch = batch.to(dist_util.dev()) 110 | emb = encoder.encode(batch).sample().half() 111 | emb *= 0.18215 112 | 113 | yield emb, model_kwargs 114 | 115 | def create_argparser(): 116 | defaults = dict( 117 | data_dir="", 118 | schedule_sampler="uniform", 119 | lr=1e-4, 120 | weight_decay=0.0, 121 | lr_anneal_steps=0, 122 | batch_size=1, 123 | microbatch=-1, # -1 disables microbatches 124 | ema_rate="0.9999", # comma-separated list of EMA values 125 | log_interval=10, 126 | save_interval=10000, 127 | resume_checkpoint="", 128 | use_fp16=False, 129 | fp16_scale_growth=1e-3, 130 | kl_model=None, 131 | bert_model=None, 132 | ) 133 | defaults.update(model_and_diffusion_defaults()) 134 | parser = argparse.ArgumentParser() 135 | add_dict_to_argparser(parser, defaults) 136 | return parser 137 | 138 | 139 | if __name__ == "__main__": 140 | main() 141 | -------------------------------------------------------------------------------- /scripts/super_res_sample.py: -------------------------------------------------------------------------------- 1 | """ 2 | Generate a large batch of samples from a super resolution model, given a batch 3 | of samples from a regular model from image_sample.py. 4 | """ 5 | 6 | import argparse 7 | import os 8 | 9 | import blobfile as bf 10 | import numpy as np 11 | import torch as th 12 | import torch.distributed as dist 13 | 14 | from guided_diffusion import dist_util, logger 15 | from guided_diffusion.script_util import ( 16 | sr_model_and_diffusion_defaults, 17 | sr_create_model_and_diffusion, 18 | args_to_dict, 19 | add_dict_to_argparser, 20 | ) 21 | 22 | 23 | def main(): 24 | args = create_argparser().parse_args() 25 | 26 | dist_util.setup_dist() 27 | logger.configure() 28 | 29 | logger.log("creating model...") 30 | model, diffusion = sr_create_model_and_diffusion( 31 | **args_to_dict(args, sr_model_and_diffusion_defaults().keys()) 32 | ) 33 | model.load_state_dict( 34 | dist_util.load_state_dict(args.model_path, map_location="cpu") 35 | ) 36 | model.to(dist_util.dev()) 37 | if args.use_fp16: 38 | model.convert_to_fp16() 39 | model.eval() 40 | 41 | logger.log("loading data...") 42 | data = load_data_for_worker(args.base_samples, args.batch_size, args.class_cond) 43 | 44 | logger.log("creating samples...") 45 | all_images = [] 46 | while len(all_images) * args.batch_size < args.num_samples: 47 | model_kwargs = next(data) 48 | model_kwargs = {k: v.to(dist_util.dev()) for k, v in model_kwargs.items()} 49 | sample = diffusion.p_sample_loop( 50 | model, 51 | (args.batch_size, 3, args.large_size, args.large_size), 52 | clip_denoised=args.clip_denoised, 53 | model_kwargs=model_kwargs, 54 | ) 55 | sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8) 56 | sample = sample.permute(0, 2, 3, 1) 57 | sample = sample.contiguous() 58 | 59 | all_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())] 60 | dist.all_gather(all_samples, sample) # gather not supported with NCCL 61 | for sample in all_samples: 62 | all_images.append(sample.cpu().numpy()) 63 | logger.log(f"created {len(all_images) * args.batch_size} samples") 64 | 65 | arr = np.concatenate(all_images, axis=0) 66 | arr = arr[: args.num_samples] 67 | if dist.get_rank() == 0: 68 | shape_str = "x".join([str(x) for x in arr.shape]) 69 | out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz") 70 | logger.log(f"saving to {out_path}") 71 | np.savez(out_path, arr) 72 | 73 | dist.barrier() 74 | logger.log("sampling complete") 75 | 76 | 77 | def load_data_for_worker(base_samples, batch_size, class_cond): 78 | with bf.BlobFile(base_samples, "rb") as f: 79 | obj = np.load(f) 80 | image_arr = obj["arr_0"] 81 | if class_cond: 82 | label_arr = obj["arr_1"] 83 | rank = dist.get_rank() 84 | num_ranks = dist.get_world_size() 85 | buffer = [] 86 | label_buffer = [] 87 | while True: 88 | for i in range(rank, len(image_arr), num_ranks): 89 | buffer.append(image_arr[i]) 90 | if class_cond: 91 | label_buffer.append(label_arr[i]) 92 | if len(buffer) == batch_size: 93 | batch = th.from_numpy(np.stack(buffer)).float() 94 | batch = batch / 127.5 - 1.0 95 | batch = batch.permute(0, 3, 1, 2) 96 | res = dict(low_res=batch) 97 | if class_cond: 98 | res["y"] = th.from_numpy(np.stack(label_buffer)) 99 | yield res 100 | buffer, label_buffer = [], [] 101 | 102 | 103 | def create_argparser(): 104 | defaults = dict( 105 | clip_denoised=True, 106 | num_samples=10000, 107 | batch_size=16, 108 | use_ddim=False, 109 | base_samples="", 110 | model_path="", 111 | ) 112 | defaults.update(sr_model_and_diffusion_defaults()) 113 | parser = argparse.ArgumentParser() 114 | add_dict_to_argparser(parser, defaults) 115 | return parser 116 | 117 | 118 | if __name__ == "__main__": 119 | main() 120 | -------------------------------------------------------------------------------- /scripts/super_res_train.py: -------------------------------------------------------------------------------- 1 | """ 2 | Train a super-resolution model. 3 | """ 4 | 5 | import argparse 6 | 7 | import torch.nn.functional as F 8 | 9 | from guided_diffusion import dist_util, logger 10 | from guided_diffusion.image_datasets import load_data 11 | from guided_diffusion.resample import create_named_schedule_sampler 12 | from guided_diffusion.script_util import ( 13 | sr_model_and_diffusion_defaults, 14 | sr_create_model_and_diffusion, 15 | args_to_dict, 16 | add_dict_to_argparser, 17 | ) 18 | from guided_diffusion.train_util import TrainLoop 19 | 20 | 21 | def main(): 22 | args = create_argparser().parse_args() 23 | 24 | dist_util.setup_dist() 25 | logger.configure() 26 | 27 | logger.log("creating model...") 28 | model, diffusion = sr_create_model_and_diffusion( 29 | **args_to_dict(args, sr_model_and_diffusion_defaults().keys()) 30 | ) 31 | model.to(dist_util.dev()) 32 | schedule_sampler = create_named_schedule_sampler(args.schedule_sampler, diffusion) 33 | 34 | logger.log("creating data loader...") 35 | data = load_superres_data( 36 | args.data_dir, 37 | args.batch_size, 38 | large_size=args.large_size, 39 | small_size=args.small_size, 40 | class_cond=args.class_cond, 41 | ) 42 | 43 | logger.log("training...") 44 | TrainLoop( 45 | model=model, 46 | diffusion=diffusion, 47 | data=data, 48 | batch_size=args.batch_size, 49 | microbatch=args.microbatch, 50 | lr=args.lr, 51 | ema_rate=args.ema_rate, 52 | log_interval=args.log_interval, 53 | save_interval=args.save_interval, 54 | resume_checkpoint=args.resume_checkpoint, 55 | use_fp16=args.use_fp16, 56 | fp16_scale_growth=args.fp16_scale_growth, 57 | schedule_sampler=schedule_sampler, 58 | weight_decay=args.weight_decay, 59 | lr_anneal_steps=args.lr_anneal_steps, 60 | ).run_loop() 61 | 62 | 63 | def load_superres_data(data_dir, batch_size, large_size, small_size, class_cond=False): 64 | data = load_data( 65 | data_dir=data_dir, 66 | batch_size=batch_size, 67 | image_size=large_size, 68 | class_cond=class_cond, 69 | ) 70 | for large_batch, model_kwargs in data: 71 | model_kwargs["low_res"] = F.interpolate(large_batch, small_size, mode="area") 72 | yield large_batch, model_kwargs 73 | 74 | 75 | def create_argparser(): 76 | defaults = dict( 77 | data_dir="", 78 | schedule_sampler="uniform", 79 | lr=1e-4, 80 | weight_decay=0.0, 81 | lr_anneal_steps=0, 82 | batch_size=1, 83 | microbatch=-1, 84 | ema_rate="0.9999", 85 | log_interval=10, 86 | save_interval=10000, 87 | resume_checkpoint="", 88 | use_fp16=False, 89 | fp16_scale_growth=1e-3, 90 | ) 91 | defaults.update(sr_model_and_diffusion_defaults()) 92 | parser = argparse.ArgumentParser() 93 | add_dict_to_argparser(parser, defaults) 94 | return parser 95 | 96 | 97 | if __name__ == "__main__": 98 | main() 99 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name="guided-diffusion", 5 | py_modules=["guided_diffusion"], 6 | install_requires=["blobfile>=1.0.5", "torch", "tqdm"], 7 | ) 8 | --------------------------------------------------------------------------------