Yewon Lim commited on
Commit
424919d
·
1 Parent(s): e135651
Files changed (47) hide show
  1. Dockerfile +19 -0
  2. DockerfileOcto +31 -0
  3. README.md +129 -0
  4. check_compress.py +42 -0
  5. compute_dire_eps.sh +15 -0
  6. custommodel.py +173 -0
  7. dataset/__init__.py +1 -0
  8. dataset/test.ipynb +85 -0
  9. dataset/truemedia_dataset.py +147 -0
  10. datasets/README.md +1 -0
  11. deploy_utils/check_stat.py +63 -0
  12. deploy_utils/check_stat_comp.py +74 -0
  13. deploy_utils/concat.py +32 -0
  14. deploy_utils/crawl.py +68 -0
  15. deploy_utils/crawl_civt.py +103 -0
  16. deploy_utils/down.py +16 -0
  17. deploy_utils/instaimages_format.py +18 -0
  18. distil.png +0 -0
  19. guided_diffusion/LICENSE +21 -0
  20. guided_diffusion/README.md +176 -0
  21. guided_diffusion/compute_dire_eps.py +266 -0
  22. guided_diffusion/guided_diffusion/__init__.py +3 -0
  23. guided_diffusion/guided_diffusion/dist_util.py +99 -0
  24. guided_diffusion/guided_diffusion/fp16_util.py +237 -0
  25. guided_diffusion/guided_diffusion/gaussian_diffusion.py +1038 -0
  26. guided_diffusion/guided_diffusion/image_datasets.py +266 -0
  27. guided_diffusion/guided_diffusion/logger.py +495 -0
  28. guided_diffusion/guided_diffusion/losses.py +77 -0
  29. guided_diffusion/guided_diffusion/nn.py +170 -0
  30. guided_diffusion/guided_diffusion/resample.py +154 -0
  31. guided_diffusion/guided_diffusion/respace.py +128 -0
  32. guided_diffusion/guided_diffusion/script_util.py +456 -0
  33. guided_diffusion/guided_diffusion/train_util.py +301 -0
  34. guided_diffusion/guided_diffusion/unet.py +897 -0
  35. guided_diffusion/model-card.md +59 -0
  36. guided_diffusion/setup.py +7 -0
  37. networks/distill_model.py +76 -0
  38. requirements.txt +21 -0
  39. server.py +55 -0
  40. test.py +22 -0
  41. train.py +59 -0
  42. train.sh +3 -0
  43. utils/config.py +179 -0
  44. utils/sanic_utils.py +88 -0
  45. utils/trainer.py +329 -0
  46. utils/utils.py +47 -0
  47. utils/warmup.py +70 -0
Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu22.04
2
+
3
+ RUN apt-get update && apt-get install -y \
4
+ python3-pip \
5
+ libgl1-mesa-glx \
6
+ libglib2.0-0 python3-dev libglib2.0-0 libgl1-mesa-glx \
7
+ cmake tmux git curl wget gcc build-essential \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ RUN pip install --no-cache-dir --upgrade pip
11
+ RUN pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 --index-url https://download.pytorch.org/whl/cu121
12
+ ADD requirements.txt requirements.txt
13
+ RUN pip install --no-cache-dir -r requirements.txt
14
+ WORKDIR /workspace
15
+
16
+
17
+
18
+
19
+
DockerfileOcto ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu22.04
2
+
3
+ RUN apt-get update && apt-get install -y \
4
+ python3-pip \
5
+ libgl1-mesa-glx \
6
+ libglib2.0-0 python3-dev libglib2.0-0 libgl1-mesa-glx \
7
+ cmake tmux git curl wget gcc build-essential \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ WORKDIR /app
11
+ RUN pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 --index-url https://download.pytorch.org/whl/cu121
12
+ ADD requirements.txt /app/requirements.txt
13
+ RUN pip install --no-cache-dir -r requirements.txt
14
+
15
+ ADD guided_diffusion/ /app/guided_diffusion
16
+ ADD dataset/ /app/dataset
17
+ ADD networks/ /app/networks
18
+ ADD utils/ /app/utils
19
+ ADD models /app/models
20
+ ADD server.py /app/server.py
21
+
22
+ ADD custommodel.py /app/custommodel.py
23
+
24
+
25
+ ARG SERVING_PORT=8000
26
+ ENV SERVING_PORT=$SERVING_PORT
27
+ EXPOSE $SERVING_PORT
28
+
29
+ CMD python3 -m server
30
+
31
+
README.md ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Distil-DIRE
2
+ Distil-DIRE is a lightweight version of DIRE, which can be used for real-time applications. Instead of calculating DIRE image directly, Distl-DIRE aims to reconstruct the features of corresponding DIRE image forwared by a image-net pretrained classifier with one-step noise of DDIM inversion. ([Paper Link](https://arxiv.org/abs/2406.00856))
3
+ ![overview](distil.png)
4
+
5
+ ### Pretrained DistilDIRE Checkpoints
6
+ | Dataset | Model | Link |
7
+ | --- | --- | --- |
8
+ | CelebA-HQ | 224x224 | [link]() |
9
+ | ImageNet | 224x224 | [link]() |
10
+
11
+
12
+
13
+
14
+ ## Pretrained ADM diffusion model
15
+ We use image-net pretrained unconditional ADM diffusion model for feature reconstruction. You can download the pretrained model from the following link:
16
+ https://openaipublic.blob.core.windows.net/diffusion/jul-2021/512x512_diffusion.pt
17
+
18
+ or you can use the following script to download the model:
19
+ ```bash
20
+ wget https://openaipublic.blob.core.windows.net/diffusion/jul-2021/512x512_diffusion.pt -O models/512x512-adm.pt
21
+ ```
22
+
23
+ ## Data Preparation
24
+ Before training the model on your own dataset, you need to prepare the dataset in the following format:
25
+ ```bash
26
+ mydataset/train|val|test
27
+ └── images
28
+ ├── fakes
29
+ │ └──img1.png...
30
+ ├── reals
31
+ └──rimg1.png...
32
+ ```
33
+
34
+ After preparing the dataset, you can calculate the epsilons and dire images for the dataset using the following script:
35
+ ```bash
36
+ bash compute_dire_eps.sh
37
+ ```
38
+
39
+ After running the script, you will have the following directory structure:
40
+ ```bash
41
+ mydataset/train|val|test
42
+ └── images
43
+ ├── fakes
44
+ │ └──img1.png...
45
+ ├── reals
46
+ └──rimg1.png...
47
+ └── eps
48
+ ├── fakes
49
+ │ └──img1.pt...
50
+ ├── reals
51
+ └──rimg1.pt...
52
+ └── dire
53
+ ├── fakes
54
+ │ └──img1.png...
55
+ ├── reals
56
+ └──rimg1.png...
57
+ ```
58
+ For eps and dire calculation we set the DDIM steps to 20. This should be same when inference.
59
+
60
+ ### Train
61
+ For training Distil-DIRE, be sure to have `datasets` directory in the root of the project and your dataset inside the `datasets` directory.
62
+ ```
63
+ torchrun --standalone --nproc_per_node 8 -m train --batch 128 --exp_name truemedia-distil-dire-mydataset --datasets mydataset --datasets_test mytestset --epoch 100 --lr 1e-4
64
+
65
+ ```
66
+
67
+ #### Fine-tuning
68
+ You can also fine-tune the model on your own dataset. For fine-tuning, you need to provide the path to the pretrained model.
69
+ ```bash
70
+ torchrun --standalone --nproc_per_node 8 -m train --batch 128 --exp_name truemedia-distil-dire-mydataset --datasets mydataset --datasets_test mytestset --epoch 100 --lr 1e-4 --pretrained_weights YOUR_PRETRAINED_MODEL_PATH
71
+ ```
72
+
73
+
74
+ ### Test
75
+ For testing the model, you can use the following script:
76
+ ```bash
77
+ python3 -m test --test True --datasets mydataset --pretrained_weights YOUR_PRETRAINED_MODEL_PATH
78
+ ```
79
+
80
+
81
+ ### with Docker
82
+ ```
83
+ export DOCKER_REGISTRY="YOUR_NAME" # Put your Docker Hub username here
84
+ export DATE=`date +%Y%m%d` # Get the current date
85
+
86
+ # Build the Docker image for development
87
+ docker build -t "$DOCKER_REGISTRY/distil-dire:dev-$DATE" -f Dockerfile .
88
+
89
+
90
+ # Push your docker image to docker hub
91
+ docker login
92
+ docker push "$DOCKER_REGISTRY/distil-dire:dev-$DATE"
93
+
94
+ ```
95
+
96
+
97
+ # Devl env
98
+ ```
99
+ export WORKDIR="YOUR_WORKDIR" # Put your working directory here
100
+ docker run --gpus=all --name=truemedia_gpu_all_distildire -v "$WORKDIR:/workspace/" -ti -e "$DOCKER_REGISTRY/distil-dire:dev-$DATE"
101
+
102
+ # work inside the container (/workspace)
103
+ ```
104
+
105
+ ### Note
106
+ * This repo runs on ADM diffusion model (256x256, unconditional) trained on ImageNet 1k dataset and ResNet-50 classifier trained on ImageNet 1k dataset.
107
+ * Minimum requirements: 1 GPU, 10GB VRAM
108
+
109
+
110
+ ## Licenses
111
+ This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 license.
112
+ You are free to read, share, and modify this code as long as you keep the original author attribution and non-commercial license.
113
+ Please see [this site](https://creativecommons.org/licenses/by-nc/4.0/) for detailed legal terms.
114
+
115
+ ## Acknowledgments
116
+ Our code is developed based on [DIRE](https://github.com/ZhendongWang6/DIRE), [guided-diffusion](https://github.com/openai/guided-diffusion) and [CNNDetection](https://github.com/peterwang512/CNNDetection). Thanks for their sharing codes and models.
117
+
118
+ ## Citation
119
+ If you find this work useful for your research, please cite our paper:
120
+ ```
121
+ @misc{lim2024distildire,
122
+ title={DistilDIRE: A Small, Fast, Cheap and Lightweight Diffusion Synthesized Deepfake Detection},
123
+ author={Yewon Lim and Changyeon Lee and Aerin Kim and Oren Etzioni},
124
+ year={2024},
125
+ eprint={2406.00856},
126
+ archivePrefix={arXiv},
127
+ primaryClass={cs.CV}
128
+ }
129
+ ```
check_compress.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import piexif
3
+
4
+ def check_image_compression(image_path):
5
+ try:
6
+ with Image.open(image_path) as img:
7
+ format = img.format
8
+ # Common compressed formats
9
+ if format in ["JPEG", "JPG", "PNG", "GIF", "WEBP"]:
10
+ print(f"The image format is {format}, which is typically compressed.")
11
+ else:
12
+ print(f"The image format is {format}, which is less likely to be compressed.")
13
+
14
+ if format in ["JPEG", "JPG"]:
15
+ print(img.info)
16
+ exif_dict = piexif.load(img.info.get('exif', ''))
17
+ if "0th" in exif_dict and piexif.ImageIFD.Compression in exif_dict["0th"]:
18
+ compression = exif_dict["0th"][piexif.ImageIFD.Compression]
19
+ if compression != 1: # 1 means uncompressed
20
+ print(f"The JPEG image is compressed. Compression value: {compression}")
21
+ else:
22
+ print("The JPEG image is not compressed.")
23
+ else:
24
+ print("No EXIF compression metadata found for JPEG image.")
25
+ elif format == "PNG":
26
+ if img.info.get("interlace"):
27
+ print("The PNG image is interlaced (which can be a form of compression).")
28
+ else:
29
+ print("The PNG image is not interlaced.")
30
+ elif format == "WEBP":
31
+ if img.info.get("lossless", False):
32
+ print("The WebP image is lossless (not compressed).")
33
+ else:
34
+ print("The WebP image is compressed.")
35
+ else:
36
+ print(f"No additional compression information available for format: {format}")
37
+ except Exception as e:
38
+ print(f"Error: {e}")
39
+
40
+ # Example usage
41
+ image_path = '/home/ubuntu/y1/DistilDIRE/datasets/truemedia-political/images/fakes/ZPNOX270fe2dJ6fHvG1mVaHwHM0.jpg' # Replace with your image path
42
+ check_image_compression(image_path)
compute_dire_eps.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## set MODEL_PATH, num_samples, has_subfolder, images_dir, recons_dir, dire_dir
2
+ DATA_ROOT=("/home/ubuntu/y1/DistilDIRE/datasets/truemedia-total")
3
+ SAVE_ROOT=("/home/ubuntu/y1/DistilDIRE/datasets/truemedia-total")
4
+
5
+ MODEL_PATH="models/256x256-adm.pt" # imagenet pretrained adm (unconditional, 512x512)
6
+ SAMPLE_FLAGS="--batch_size 32" # ddim20 is forced
7
+ PREPROCESS_FLAGS="--compute_dire True --compute_eps True"
8
+
9
+ for i in 0
10
+ do
11
+ SAVE_FLAGS="--data_root ${DATA_ROOT[$i]} --save_root ${SAVE_ROOT[$i]}"
12
+ echo "Running on ${DATA_ROOT[$i]} with save root ${SAVE_ROOT[$i]}"
13
+ torchrun --standalone --nproc_per_node 1 -m guided_diffusion.compute_dire_eps --model_path $MODEL_PATH $PREPROCESS_FLAGS $SAMPLE_FLAGS $SAVE_FLAGS
14
+ done
15
+ # torchrun --standalone --nproc_per_node 8 -m train --batch 128 --exp_name tm-global-scale --datasets y1-global-truemedia --epoch 40 --lr 1e-4
custommodel.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ from time import perf_counter
4
+ from datetime import datetime
5
+ import torchvision.transforms as transforms
6
+ from torchvision.utils import save_image
7
+ import torchvision.transforms.functional as TF
8
+ from torchvision.transforms import Compose, Resize, CenterCrop
9
+ from torchvision.io import decode_jpeg, encode_jpeg
10
+
11
+
12
+ from PIL import Image
13
+ import os
14
+ import torch
15
+ from utils.sanic_utils import *
16
+ import typing
17
+ import requests
18
+ import time # Import the time module
19
+ from guided_diffusion.compute_dire_eps import dire_get_first_step_noise, create_argparser
20
+ from networks.distill_model import DistilDIREOnlyEPS, DistilDIRE
21
+ from guided_diffusion.guided_diffusion.script_util import (
22
+ create_model_and_diffusion,
23
+ model_and_diffusion_defaults,
24
+ dict_parse
25
+ )
26
+
27
+
28
+ def download_file(input_path):
29
+ """
30
+ Download a file from a given URL and save it locally if input_path is a URL.
31
+ If input_path is a local file path and the file exists, skip the download.
32
+
33
+ :param input_path: The URL of the file to download or a local file path.
34
+ :return: The local filepath to the downloaded or existing file.
35
+ """
36
+ # Check if input_path is a URL
37
+ if input_path.startswith(('http://', 'https://')):
38
+ # Extract filename from the URL
39
+ # Splits the URL by '/' and get the last part
40
+ filename = input_path.split('/')[-1]
41
+
42
+ # Ensure the filename does not contain query parameters if present in the URL
43
+ # Splits the filename by '?' and get the first part
44
+ filename = filename.split('?')[0]
45
+
46
+ # put jpg extension if not present
47
+ if '.' not in filename:
48
+ filename += ".jpg"
49
+
50
+ # Define the local path where the file will be saved
51
+ local_filepath = os.path.join('.', filename)
52
+
53
+ # Check if file already exists locally
54
+ if os.path.isfile(local_filepath):
55
+ print(f"The file already exists locally: {local_filepath}")
56
+ return local_filepath
57
+
58
+ # Start timing the download
59
+ start_time = time.time()
60
+
61
+ # Send a GET request to the URL
62
+ response = requests.get(input_path, stream=True)
63
+
64
+ # Raise an exception if the request was unsuccessful
65
+ response.raise_for_status()
66
+
67
+ # Open the local file in write-binary mode
68
+ with open(local_filepath, 'wb') as file:
69
+ # Write the content of the response to the local file
70
+ for chunk in response.iter_content(chunk_size=8192):
71
+ file.write(chunk)
72
+
73
+ # End timing the download
74
+ end_time = time.time()
75
+
76
+ # Calculate the download duration
77
+ download_duration = end_time - start_time
78
+
79
+ print(
80
+ f"Downloaded file saved to {local_filepath} in {download_duration:.2f} seconds.")
81
+
82
+ else:
83
+ # Assume input_path is a local file path
84
+ local_filepath = input_path
85
+ # Check if the specified local file exists
86
+ if not os.path.isfile(local_filepath):
87
+ raise FileNotFoundError(f"No such file: '{local_filepath}'")
88
+ print(f"Using existing file: {local_filepath}")
89
+
90
+ return local_filepath
91
+
92
+
93
+ class CustomModel:
94
+ """Wrapper for a DIRE model."""
95
+
96
+ def __init__(self, net='DIRE', num_frames=15, ckpt='truemedia-global-scaled.pth'):
97
+ self.net = net
98
+ self.num_frames = num_frames
99
+
100
+ # self.model = DistilDIREOnlyEPS('cuda').to('cuda')
101
+ self.model = DistilDIRE('cuda').to('cuda')
102
+ self.trans = transforms.Compose((transforms.Resize(256, antialias=True), transforms.CenterCrop((256, 256)),))
103
+
104
+ self._load_state_dict(ckpt)
105
+
106
+ args = create_argparser()
107
+ args['timestep_respacing'] = 'ddim20'
108
+ adm_model, diffusion = create_model_and_diffusion(**dict_parse(args, model_and_diffusion_defaults().keys()))
109
+ adm_model.load_state_dict(torch.load(args['model_path'], map_location="cpu"))
110
+ adm_model.cuda()
111
+ adm_model.convert_to_fp16()
112
+ adm_model.eval()
113
+ self.adm_model = adm_model
114
+ self.diffusion = diffusion
115
+ self.args = args
116
+
117
+
118
+ def _load_state_dict(self, ckpt):
119
+ print(f"Loading the model from {ckpt}...")
120
+ state_dict = torch.load(ckpt, map_location="cpu")['model']
121
+ state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()}
122
+
123
+ self.model.load_state_dict(state_dict)
124
+ self.model.eval()
125
+ self.model.cuda()
126
+ print("The model is successfully loaded")
127
+
128
+
129
+ def _forward_dire_img(self, img_path, save_dire=True, thr=0.5):
130
+ img = Image.open(img_path).convert("RGB")
131
+ img = TF.to_tensor(img)
132
+ img = self.trans(img).cuda() * 2 - 1
133
+ img = img.unsqueeze(0)
134
+ with torch.no_grad():
135
+ eps = dire_get_first_step_noise(img, self.adm_model, self.diffusion, self.args, "cuda")
136
+ # eps = eps.detach().cpu()
137
+ # ext = img_path.split('.')[-1]
138
+ # eps_path = img_path.replace(f".{ext}", ".pt")
139
+ # torch.save(eps, eps_path)
140
+
141
+ # eps = torch.load(eps_path, weights_only=True, mmap=True).cuda()
142
+ # os.remove(eps_path)
143
+ prob = self.model(img, eps)['logit'].sigmoid()
144
+
145
+ return {"df_probability": prob.median().item(), "prediction": real_or_fake_thres(prob.median().item(), thr)}
146
+
147
+
148
+ def predict(self, inputs: typing.Dict[str, str]) -> typing.Dict[str, str]:
149
+ file_path = inputs.get('file_path', None)
150
+ video_file = download_file(file_path)
151
+
152
+ if os.path.isfile(video_file):
153
+ try:
154
+ if is_image(video_file):
155
+ print(f"{self.net} is being run.")
156
+ return self._forward_dire_img(video_file)
157
+
158
+ else:
159
+ print(
160
+ f"Invalid media file: {video_file}. Please provide a valid video/img file.")
161
+ return {"msg": f"Invalid media file: {video_file}. Please provide a valid video/img file."}
162
+ except Exception as e:
163
+ print(f"An error occurred: {str(e)}")
164
+ return {"msg": f"An error occurred: {str(e)}"}
165
+ else:
166
+ print(f"The file {video_file} does not exist.")
167
+ return {"msg": f"The file {video_file} does not exist."}
168
+
169
+
170
+ @classmethod
171
+ def fetch(cls) -> None:
172
+ cls()
173
+
dataset/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .truemedia_dataset import TMDistilDireDataset, TMDireDataset, TMEPSOnlyDataset, TMIMGOnlyDataset
dataset/test.ipynb ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "data": {
10
+ "application/vnd.jupyter.widget-view+json": {
11
+ "model_id": "172d80aab4da42c8b6a723cd4fc43f6d",
12
+ "version_major": 2,
13
+ "version_minor": 0
14
+ },
15
+ "text/plain": [
16
+ " 0%| | 0/625 [00:00<?, ?it/s]"
17
+ ]
18
+ },
19
+ "metadata": {},
20
+ "output_type": "display_data"
21
+ },
22
+ {
23
+ "ename": "KeyboardInterrupt",
24
+ "evalue": "",
25
+ "output_type": "error",
26
+ "traceback": [
27
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
28
+ "\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)",
29
+ "Cell \u001b[0;32mIn[1], line 11\u001b[0m\n\u001b[1;32m 8\u001b[0m dataloader \u001b[38;5;241m=\u001b[39m DataLoader(dataset, batch_size\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m128\u001b[39m, shuffle\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m, num_workers\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m4\u001b[39m)\n\u001b[1;32m 10\u001b[0m st \u001b[38;5;241m=\u001b[39m time\u001b[38;5;241m.\u001b[39mtime()\n\u001b[0;32m---> 11\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m _ \u001b[38;5;129;01min\u001b[39;00m tqdm(dataloader):\n\u001b[1;32m 12\u001b[0m \u001b[38;5;28;01mpass\u001b[39;00m\n\u001b[1;32m 14\u001b[0m end \u001b[38;5;241m=\u001b[39m time\u001b[38;5;241m.\u001b[39mtime()\n",
30
+ "File \u001b[0;32m/usr/local/lib/python3.10/dist-packages/tqdm/notebook.py:250\u001b[0m, in \u001b[0;36mtqdm_notebook.__iter__\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 248\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m 249\u001b[0m it \u001b[38;5;241m=\u001b[39m \u001b[38;5;28msuper\u001b[39m(tqdm_notebook, \u001b[38;5;28mself\u001b[39m)\u001b[38;5;241m.\u001b[39m\u001b[38;5;21m__iter__\u001b[39m()\n\u001b[0;32m--> 250\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m obj \u001b[38;5;129;01min\u001b[39;00m it:\n\u001b[1;32m 251\u001b[0m \u001b[38;5;66;03m# return super(tqdm...) will not catch exception\u001b[39;00m\n\u001b[1;32m 252\u001b[0m \u001b[38;5;28;01myield\u001b[39;00m obj\n\u001b[1;32m 253\u001b[0m \u001b[38;5;66;03m# NB: except ... [ as ...] breaks IPython async KeyboardInterrupt\u001b[39;00m\n",
31
+ "File \u001b[0;32m/usr/local/lib/python3.10/dist-packages/tqdm/std.py:1181\u001b[0m, in \u001b[0;36mtqdm.__iter__\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 1178\u001b[0m time \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_time\n\u001b[1;32m 1180\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m-> 1181\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m obj \u001b[38;5;129;01min\u001b[39;00m iterable:\n\u001b[1;32m 1182\u001b[0m \u001b[38;5;28;01myield\u001b[39;00m obj\n\u001b[1;32m 1183\u001b[0m \u001b[38;5;66;03m# Update and possibly print the progressbar.\u001b[39;00m\n\u001b[1;32m 1184\u001b[0m \u001b[38;5;66;03m# Note: does not call self.update(1) for speed optimisation.\u001b[39;00m\n",
32
+ "File \u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/utils/data/dataloader.py:631\u001b[0m, in \u001b[0;36m_BaseDataLoaderIter.__next__\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 628\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_sampler_iter \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 629\u001b[0m \u001b[38;5;66;03m# TODO(https://github.com/pytorch/pytorch/issues/76750)\u001b[39;00m\n\u001b[1;32m 630\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_reset() \u001b[38;5;66;03m# type: ignore[call-arg]\u001b[39;00m\n\u001b[0;32m--> 631\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_next_data\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 632\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_num_yielded \u001b[38;5;241m+\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[1;32m 633\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_dataset_kind \u001b[38;5;241m==\u001b[39m _DatasetKind\u001b[38;5;241m.\u001b[39mIterable \u001b[38;5;129;01mand\u001b[39;00m \\\n\u001b[1;32m 634\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_IterableDataset_len_called \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m \\\n\u001b[1;32m 635\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_num_yielded \u001b[38;5;241m>\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_IterableDataset_len_called:\n",
33
+ "File \u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/utils/data/dataloader.py:1329\u001b[0m, in \u001b[0;36m_MultiProcessingDataLoaderIter._next_data\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 1326\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_process_data(data)\n\u001b[1;32m 1328\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_shutdown \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tasks_outstanding \u001b[38;5;241m>\u001b[39m \u001b[38;5;241m0\u001b[39m\n\u001b[0;32m-> 1329\u001b[0m idx, data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_get_data\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1330\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tasks_outstanding \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[1;32m 1331\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_dataset_kind \u001b[38;5;241m==\u001b[39m _DatasetKind\u001b[38;5;241m.\u001b[39mIterable:\n\u001b[1;32m 1332\u001b[0m \u001b[38;5;66;03m# Check for _IterableDatasetStopIteration\u001b[39;00m\n",
34
+ "File \u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/utils/data/dataloader.py:1295\u001b[0m, in \u001b[0;36m_MultiProcessingDataLoaderIter._get_data\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 1291\u001b[0m \u001b[38;5;66;03m# In this case, `self._data_queue` is a `queue.Queue`,. But we don't\u001b[39;00m\n\u001b[1;32m 1292\u001b[0m \u001b[38;5;66;03m# need to call `.task_done()` because we don't use `.join()`.\u001b[39;00m\n\u001b[1;32m 1293\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 1294\u001b[0m \u001b[38;5;28;01mwhile\u001b[39;00m \u001b[38;5;28;01mTrue\u001b[39;00m:\n\u001b[0;32m-> 1295\u001b[0m success, data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_try_get_data\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1296\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m success:\n\u001b[1;32m 1297\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m data\n",
35
+ "File \u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/utils/data/dataloader.py:1133\u001b[0m, in \u001b[0;36m_MultiProcessingDataLoaderIter._try_get_data\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m 1120\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m_try_get_data\u001b[39m(\u001b[38;5;28mself\u001b[39m, timeout\u001b[38;5;241m=\u001b[39m_utils\u001b[38;5;241m.\u001b[39mMP_STATUS_CHECK_INTERVAL):\n\u001b[1;32m 1121\u001b[0m \u001b[38;5;66;03m# Tries to fetch data from `self._data_queue` once for a given timeout.\u001b[39;00m\n\u001b[1;32m 1122\u001b[0m \u001b[38;5;66;03m# This can also be used as inner loop of fetching without timeout, with\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 1130\u001b[0m \u001b[38;5;66;03m# Returns a 2-tuple:\u001b[39;00m\n\u001b[1;32m 1131\u001b[0m \u001b[38;5;66;03m# (bool: whether successfully get data, any: data if successful else None)\u001b[39;00m\n\u001b[1;32m 1132\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m-> 1133\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_data_queue\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtimeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtimeout\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1134\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m (\u001b[38;5;28;01mTrue\u001b[39;00m, data)\n\u001b[1;32m 1135\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 1136\u001b[0m \u001b[38;5;66;03m# At timeout and error, we manually check whether any worker has\u001b[39;00m\n\u001b[1;32m 1137\u001b[0m \u001b[38;5;66;03m# failed. Note that this is the only mechanism for Windows to detect\u001b[39;00m\n\u001b[1;32m 1138\u001b[0m \u001b[38;5;66;03m# worker failures.\u001b[39;00m\n",
36
+ "File \u001b[0;32m/usr/lib/python3.10/multiprocessing/queues.py:113\u001b[0m, in \u001b[0;36mQueue.get\u001b[0;34m(self, block, timeout)\u001b[0m\n\u001b[1;32m 111\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m block:\n\u001b[1;32m 112\u001b[0m timeout \u001b[38;5;241m=\u001b[39m deadline \u001b[38;5;241m-\u001b[39m time\u001b[38;5;241m.\u001b[39mmonotonic()\n\u001b[0;32m--> 113\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_poll\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtimeout\u001b[49m\u001b[43m)\u001b[49m:\n\u001b[1;32m 114\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m Empty\n\u001b[1;32m 115\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_poll():\n",
37
+ "File \u001b[0;32m/usr/lib/python3.10/multiprocessing/connection.py:257\u001b[0m, in \u001b[0;36m_ConnectionBase.poll\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m 255\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_check_closed()\n\u001b[1;32m 256\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_check_readable()\n\u001b[0;32m--> 257\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_poll\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtimeout\u001b[49m\u001b[43m)\u001b[49m\n",
38
+ "File \u001b[0;32m/usr/lib/python3.10/multiprocessing/connection.py:424\u001b[0m, in \u001b[0;36mConnection._poll\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m 423\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m_poll\u001b[39m(\u001b[38;5;28mself\u001b[39m, timeout):\n\u001b[0;32m--> 424\u001b[0m r \u001b[38;5;241m=\u001b[39m \u001b[43mwait\u001b[49m\u001b[43m(\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtimeout\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 425\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mbool\u001b[39m(r)\n",
39
+ "File \u001b[0;32m/usr/lib/python3.10/multiprocessing/connection.py:931\u001b[0m, in \u001b[0;36mwait\u001b[0;34m(object_list, timeout)\u001b[0m\n\u001b[1;32m 928\u001b[0m deadline \u001b[38;5;241m=\u001b[39m time\u001b[38;5;241m.\u001b[39mmonotonic() \u001b[38;5;241m+\u001b[39m timeout\n\u001b[1;32m 930\u001b[0m \u001b[38;5;28;01mwhile\u001b[39;00m \u001b[38;5;28;01mTrue\u001b[39;00m:\n\u001b[0;32m--> 931\u001b[0m ready \u001b[38;5;241m=\u001b[39m \u001b[43mselector\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mselect\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtimeout\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 932\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m ready:\n\u001b[1;32m 933\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m [key\u001b[38;5;241m.\u001b[39mfileobj \u001b[38;5;28;01mfor\u001b[39;00m (key, events) \u001b[38;5;129;01min\u001b[39;00m ready]\n",
40
+ "File \u001b[0;32m/usr/lib/python3.10/selectors.py:416\u001b[0m, in \u001b[0;36m_PollLikeSelector.select\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m 414\u001b[0m ready \u001b[38;5;241m=\u001b[39m []\n\u001b[1;32m 415\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 416\u001b[0m fd_event_list \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_selector\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mpoll\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtimeout\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 417\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mInterruptedError\u001b[39;00m:\n\u001b[1;32m 418\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m ready\n",
41
+ "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
42
+ ]
43
+ }
44
+ ],
45
+ "source": [
46
+ "from truemedia_dataset import TMDistilDireDataset\n",
47
+ "from torch.utils.data import DataLoader\n",
48
+ "import time \n",
49
+ "from tqdm.auto import tqdm \n",
50
+ "\n",
51
+ "\n",
52
+ "dataset= TMDistilDireDataset(\"/workspace/DistilDIRE/datasets/distil-train-imagenet\")\n",
53
+ "dataloader = DataLoader(dataset, batch_size=128, shuffle=True, num_workers=4)\n",
54
+ "\n",
55
+ "st = time.time()\n",
56
+ "for _ in tqdm(dataloader):\n",
57
+ " pass\n",
58
+ "\n",
59
+ "end = time.time()\n",
60
+ "print(f\"Time taken: {end-st:.2f} seconds\")"
61
+ ]
62
+ }
63
+ ],
64
+ "metadata": {
65
+ "kernelspec": {
66
+ "display_name": "Python 3",
67
+ "language": "python",
68
+ "name": "python3"
69
+ },
70
+ "language_info": {
71
+ "codemirror_mode": {
72
+ "name": "ipython",
73
+ "version": 3
74
+ },
75
+ "file_extension": ".py",
76
+ "mimetype": "text/x-python",
77
+ "name": "python",
78
+ "nbconvert_exporter": "python",
79
+ "pygments_lexer": "ipython3",
80
+ "version": "3.10.12"
81
+ }
82
+ },
83
+ "nbformat": 4,
84
+ "nbformat_minor": 2
85
+ }
dataset/truemedia_dataset.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.utils.data import Dataset
2
+ import torch
3
+ import torchvision.transforms.functional as TF
4
+ from torchvision.transforms import Compose, Resize, CenterCrop
5
+ from torchvision.io import decode_jpeg, encode_jpeg
6
+ from glob import glob
7
+ import os.path as osp
8
+ from PIL import Image
9
+ import random
10
+ import os
11
+ TARGET_COMP = 0.1
12
+
13
+ class TMDistilDireDataset(Dataset):
14
+ def __init__(self, root, prepared_dire=True):
15
+ self.root = root
16
+ self.__fake_img_paths = [p for p in glob(osp.join(root, 'images/fakes/', '*')) if p.split('.')[-1].lower() in ['jpg', 'jpeg', 'png', 'webp']]
17
+ self.__real_img_paths = [p for p in glob(osp.join(root, 'images/reals/', '*')) if p.split('.')[-1].lower() in ['jpg', 'jpeg', 'png', 'webp']]
18
+ self.prepared_dire = prepared_dire
19
+ self.transform = Compose([Resize(256, antialias='True'), CenterCrop((256, 256))])
20
+
21
+
22
+ # (imgs, dire, eps, isfake)
23
+ if prepared_dire:
24
+ self.fake_paths = list(map(lambda x: (x, x.replace('/images/', '/dire/'), x.replace('/images/', '/eps/').split('.')[0]+'.pt', True), self.__fake_img_paths))
25
+ self.real_paths = list(map(lambda x: (x, x.replace('/images/', '/dire/'), x.replace('/images/', '/eps/').split('.')[0]+'.pt', False), self.__real_img_paths))
26
+ else:
27
+ self.fake_paths = list(map(lambda x: (x, "", "", True), self.__fake_img_paths))
28
+ self.real_paths = list(map(lambda x: (x, "", "", False), self.__real_img_paths))
29
+ random.shuffle(self.fake_paths)
30
+ random.shuffle(self.real_paths)
31
+ self.img_paths = self.fake_paths + self.real_paths
32
+ # if len(self.real_paths) > len(self.fake_paths) * 3:
33
+ # self.img_paths = self.fake_paths + self.real_paths[:len(self.fake_paths) * 3]
34
+
35
+ img_paths = []
36
+ for img_path, dire_path, eps_path, isfake in self.img_paths:
37
+ try:
38
+ Image.open(img_path)
39
+ img_paths.append((img_path, dire_path, eps_path, isfake))
40
+ except:
41
+ continue
42
+ self.img_paths = img_paths
43
+
44
+ def __len__(self):
45
+ return len(self.img_paths)
46
+
47
+ def __getitem__(self, idx):
48
+ img_path, dire_path, eps_path, isfake = self.img_paths[idx]
49
+ img = Image.open(img_path).convert('RGB')
50
+ # w, h = img.size
51
+ # fsize = os.stat(img_path).st_size
52
+
53
+ # img = (TF.to_tensor(img)*255).to(torch.uint8)
54
+
55
+ # comp = fsize/(w*h)
56
+ # comp_quality = min(TARGET_COMP/comp * 100, 100)
57
+ # comp_quality = max(comp_quality, 1)
58
+ # img = decode_jpeg(encode_jpeg(img, quality=int(comp_quality)))
59
+ # img = img / 255.
60
+ img = TF.to_tensor(img)*2 - 1
61
+
62
+
63
+ if self.prepared_dire:
64
+ img = self.transform(img)
65
+ dire = Image.open(dire_path).convert('RGB')
66
+ dire = TF.to_tensor(dire)*2 - 1
67
+ dire = self.transform(dire)
68
+ eps = torch.load(eps_path, weights_only=True, mmap=True)
69
+ # eps = torch.zeros_like(img)
70
+ assert img.shape[1:] == dire.shape[1:] == eps.shape[1:], f"Shape mismatch: {img.shape[1:]}, {dire.shape[1:]}, {eps.shape[1:]}"
71
+
72
+ else:
73
+ img = self.transform(img)
74
+ dire = torch.zeros_like(img)
75
+ eps = torch.zeros_like(img)
76
+
77
+ return (img, dire, eps, isfake), (img_path, dire_path, eps_path)
78
+
79
+
80
+
81
+ class TMIMGOnlyDataset(TMDistilDireDataset):
82
+ def __init__(self, root, istrain=True):
83
+ super().__init__(root, prepared_dire=True)
84
+ self.istrain=istrain
85
+
86
+ def __getitem__(self, idx):
87
+
88
+ img_path, dire_path, eps_path, isfake = self.img_paths[idx]
89
+ img = Image.open(img_path).convert('RGB')
90
+ img = self.transform(img)
91
+ img = TF.to_tensor(img)*2 - 1
92
+ eps = torch.zeros_like(img)
93
+ dire = torch.zeros_like(img)
94
+
95
+ if torch.rand(1) < 0.3 and self.istrain:
96
+ img = TF.hflip(img)
97
+ return (img, dire, eps, isfake), (img_path, dire_path, eps_path)
98
+
99
+
100
+
101
+
102
+ class TMEPSOnlyDataset(TMDistilDireDataset):
103
+ def __init__(self, root, istrain=True):
104
+ super().__init__(root, prepared_dire=True)
105
+ img_paths = []
106
+ for img_path, dire_path, eps_path, isfake in self.img_paths:
107
+ if not osp.exists(eps_path) or not osp.exists(img_path):
108
+ # print(f"File not found: {eps_path} or {img_path}")
109
+ continue
110
+ try:
111
+ eps = torch.load(eps_path, weights_only=True, mmap=True)
112
+ img_paths.append((img_path, dire_path, eps_path, isfake))
113
+ except Exception as e:
114
+ print(e)
115
+ continue
116
+ self.img_paths = img_paths
117
+ self.istrain=istrain
118
+
119
+ def __getitem__(self, idx):
120
+
121
+ img_path, dire_path, eps_path, isfake = self.img_paths[idx]
122
+ img = Image.open(img_path).convert('RGB')
123
+ img = TF.to_tensor(img)*2 - 1
124
+ img = self.transform(img)
125
+ eps = torch.load(eps_path, weights_only=True, mmap=True)
126
+ dire = torch.zeros_like(img)
127
+
128
+ if torch.rand(1) < 0.3 and self.istrain:
129
+ img = TF.hflip(img)
130
+ eps = TF.hflip(eps)
131
+
132
+ return (img, dire, eps, isfake), (img_path, dire_path, eps_path)
133
+
134
+
135
+ # This is for reproducing DIRE results
136
+ class TMDireDataset(TMDistilDireDataset):
137
+ def __init__(self, root):
138
+ super().__init__(root, prepared_dire=True)
139
+
140
+ def __getitem__(self, idx):
141
+ img_path, dire_path, eps_path, isfake = self.img_paths[idx]
142
+
143
+ dire = Image.open(dire_path).convert('RGB')
144
+ dire = TF.to_tensor(dire)*2 - 1
145
+
146
+ return (dire, isfake), (dire_path,)
147
+
datasets/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ Please locate your dataset folder inside this directory.
deploy_utils/check_stat.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # create image resolution histogram
2
+
3
+ from glob import glob
4
+ from PIL import Image
5
+ from tqdm.auto import tqdm
6
+
7
+
8
+ tmfiles_f = glob("/truemedia-eval/images/fakes/*")
9
+ tmfiles_r = glob("/truemedia-eval/images/reals/*")
10
+
11
+ files_f = glob("/home/ubuntu/Datasets/diffusiondb/train/*")
12
+ files_r = glob("/home/ubuntu/Datasets/ffhq/in-the-wild-images/train/*")
13
+ files_f += glob("/home/ubuntu/Datasets/stylegan2-ffhq/train/*")
14
+ files_r += glob("/home/ubuntu/Datasets/coco-2017-train/train2017/train/*")
15
+ Ws_f = []
16
+ Hs_f = []
17
+ for f in tqdm(files_f):
18
+ img = Image.open(f)
19
+ w, h = img.size
20
+ Ws_f.append(w)
21
+ Hs_f.append(h)
22
+
23
+ Ws_r = []
24
+ Hs_r = []
25
+ for f in tqdm(files_r):
26
+ img = Image.open(f)
27
+ w, h = img.size
28
+ Ws_r.append(w)
29
+ Hs_r.append(h)
30
+
31
+ TMWs_r = []
32
+ TMHs_r = []
33
+ for f in tqdm(tmfiles_r):
34
+ img = Image.open(f)
35
+ w, h = img.size
36
+ TMWs_r.append(w)
37
+ TMHs_r.append(h)
38
+
39
+ TMWs_f = []
40
+ TMHs_f = []
41
+ for f in tqdm(tmfiles_f):
42
+ img = Image.open(f)
43
+ w, h = img.size
44
+ TMWs_f.append(w)
45
+ TMHs_f.append(h)
46
+
47
+ import matplotlib.pyplot as plt
48
+ import numpy as np
49
+
50
+ # plot 2d (w, h)
51
+ plt.figure(figsize=(8, 10))
52
+ plt.scatter(Ws_r, Hs_r, s=3, alpha=0.5)
53
+ plt.scatter(Ws_f, Hs_f, s=3, alpha=0.5, c='g')
54
+ plt.scatter(TMWs_r, TMHs_r, s=3, alpha=0.5, c='r')
55
+ plt.scatter(TMWs_f, TMHs_f, s=3, alpha=0.5, c='y')
56
+
57
+
58
+ plt.xlabel('Width')
59
+ plt.ylabel('Height')
60
+ plt.legend(['Training-real', 'Training-fake', 'TrueMedia-real', 'TrueMedia-fake'])
61
+ # save
62
+ plt.savefig('resolution_hist.png')
63
+
deploy_utils/check_stat_comp.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # create image resolution histogram
2
+
3
+ from glob import glob
4
+ from PIL import Image
5
+ from tqdm.auto import tqdm
6
+ import os
7
+
8
+ tmfiles_f = glob("/home/ubuntu/y1/DistilDIRE/datasets/truemedia-political/images/fakes/*")
9
+ tmfiles_r = glob("/home/ubuntu/y1/DistilDIRE/datasets/truemedia-political/images/reals/*")
10
+
11
+ files_f = glob("/home/ubuntu/y1/DistilDIRE/datasets/y1-global-truemedia/images/fakes/*")
12
+ files_r = glob("/truemedia-eval/y1dataset/images/reals/*")
13
+ # files_f += glob("/home/ubuntu/Datasets/stylegan2-ffhq/train/*")
14
+ # files_r += glob("/home/ubuntu/Datasets/coco-2017-train/train2017/train/*")
15
+ training_f = []
16
+ fake_cnt = 0
17
+ real_cnt = 0
18
+ for f in tqdm(files_f):
19
+ b = os.stat(f).st_size
20
+ img = Image.open(f)
21
+ w, h = img.size
22
+ if (b/(w*h)) < 1:
23
+ fake_cnt += 1
24
+ training_f.append(b/(w*h))
25
+
26
+ training_r = []
27
+ for f in tqdm(files_r):
28
+ try:
29
+ img = Image.open(f)
30
+ b = os.stat(f).st_size
31
+ w, h = img.size
32
+ if (b/(w*h)) < 1:
33
+ real_cnt += 1
34
+ training_r.append(b/(w*h))
35
+ except:
36
+ continue
37
+
38
+ TM_r = []
39
+ for f in tqdm(tmfiles_r):
40
+ try:
41
+ img = Image.open(f)
42
+ b = os.stat(f).st_size
43
+ w, h = img.size
44
+ TM_r.append(b/(w*h))
45
+ except:
46
+ continue
47
+
48
+ TM_f = []
49
+ for f in tqdm(tmfiles_f):
50
+ try:
51
+ img = Image.open(f)
52
+ b = os.stat(f).st_size
53
+ w, h = img.size
54
+ TM_f.append(b/(w*h))
55
+ except:
56
+ continue
57
+
58
+ import matplotlib.pyplot as plt
59
+ import numpy as np
60
+
61
+ # plot 2d (w, h)
62
+ plt.figure(figsize=(8, 6))
63
+ plt.hist(training_r, bins=100, alpha=0.5)
64
+ plt.hist(training_f, bins=100, alpha=0.5, color='g')
65
+ plt.hist(TM_r, bins=100, alpha=0.5, color='r')
66
+ plt.hist(TM_f, bins=100, alpha=0.5, color='y')
67
+
68
+ # Bytes/pixel
69
+ plt.xlabel('Bytes/pixel')
70
+ plt.legend(['Training-real', 'Training-fake', 'TrueMedia-real', 'TrueMedia-fake'])
71
+ # save
72
+ plt.savefig('comp_hist.png')
73
+ print(f"Training real: {real_cnt}, Training fake: {fake_cnt}")
74
+
deploy_utils/concat.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ from tqdm.auto import tqdm
3
+ import os.path as osp
4
+ from glob import glob
5
+ from PIL import Image
6
+
7
+ # PATH = "/home/ubuntu/Datasets/"
8
+ ROOTS = ['/home/ubuntu/Datasets/coco-2017-train/train2017/train', "/home/ubuntu/Datasets/ms-5kimages", "/home/ubuntu/Datasets/ffhq/in-the-wild-images/train"]
9
+ names = ['coco', 'ms-5k', 'ffhq']
10
+ DEST = "/home/ubuntu/y1/y1-global-truemedia/train/images"
11
+ skipped = 0
12
+ for name, root in zip(names, ROOTS):
13
+ # cur_path = osp.join(root, 'train/images')
14
+ # fakes = glob(osp.join(cur_path, 'fakes', '*'))
15
+ reals = glob(osp.join(root, '*'))
16
+ # for fake in fakes:
17
+ # fname = f'{root}_{osp.basename(fake)}'
18
+ # if not osp.exists(osp.join(DEST, 'fakes', fname)):
19
+ # shutil.copy(fake, osp.join(DEST, 'fakes', fname))
20
+ if name == 'coco':
21
+ reals = reals[:35000]
22
+ for real in tqdm(reals):
23
+ fname = f'{name}_{osp.basename(real)}'
24
+ size = Image.open(real).size
25
+ if max(size) > 2000:
26
+ skipped += 1
27
+ continue
28
+ if not osp.exists(osp.join(DEST, 'reals', fname)):
29
+ shutil.copy(real, osp.join(DEST, 'reals', fname))
30
+
31
+ print(f"Skipped {skipped} images for being too large.")
32
+
deploy_utils/crawl.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ from urllib.parse import urljoin
5
+ from urllib.request import urlretrieve
6
+ from tqdm.auto import tqdm
7
+ from selenium import webdriver
8
+ from selenium.webdriver.chrome.options import Options
9
+ from selenium.webdriver.common.by import By
10
+ import time
11
+
12
+ # Function to fetch and parse the webpage
13
+ def fetch_images(url, cls_name):
14
+ options = Options()
15
+ options.add_argument("--headless")
16
+ options.add_argument("window-size=1400,1500")
17
+ options.add_argument("--disable-gpu")
18
+ options.add_argument("--no-sandbox")
19
+ options.add_argument("start-maximized")
20
+ options.add_argument("enable-automation")
21
+ options.add_argument("--disable-infobars")
22
+ options.add_argument("--disable-dev-shm-usage")
23
+ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
24
+ options.add_argument(f"user-agent={user_agent}")
25
+
26
+ driver = webdriver.Chrome(options=options)
27
+ driver.get(url)
28
+ time.sleep(5)
29
+ img_elements = driver.find_elements(By.CLASS_NAME, cls_name)
30
+ urls = []
31
+ for img in img_elements:
32
+ src_url = img.get_attribute('src')
33
+ urls.append(src_url)
34
+ return urls
35
+
36
+
37
+ # Function to download images
38
+ def download_images(img_urls, download_folder='downloaded_images', desc=""):
39
+ if not os.path.exists(download_folder):
40
+ os.makedirs(download_folder)
41
+
42
+ for img_url in tqdm(img_urls, desc=desc):
43
+ fname = img_url.split('/')[-1]
44
+ fname = fname.split('?')[0]
45
+ filename = os.path.join(download_folder, fname)
46
+ urlretrieve(img_url, filename)
47
+ print(f"Downloaded: {filename}")
48
+
49
+ # Main function to coordinate the image crawling
50
+ def main():
51
+ page_n=0
52
+ while True:
53
+ page_n += 1
54
+ url = f'https://www.freepik.com/search?ai=only&format=search&last_filter=page&last_value={page_n}&page={page_n}&query=people%2C+political'
55
+ url = f'https://app.all-images.ai/en/f/images/search?pageIndex={page_n}&pageSize=40&search=man'
56
+ cls_name = "_1286nb17"
57
+ download_path = "/truemedia-eval/crawled-fakes/images/fakes"
58
+ try:
59
+ img_urls = fetch_images(url, cls_name)
60
+ if len(img_urls) == 0:
61
+ break
62
+ download_images(img_urls, download_path, desc=f"Page {page_n}")
63
+
64
+ except:
65
+ break
66
+
67
+ if __name__ == "__main__":
68
+ main()
deploy_utils/crawl_civt.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ from urllib.parse import urljoin
5
+ import urllib.request
6
+ from tqdm.auto import tqdm
7
+ from selenium import webdriver
8
+ from selenium.webdriver.chrome.options import Options
9
+ from selenium.webdriver.common.by import By
10
+ import time
11
+
12
+ # Function to fetch and parse the webpage
13
+ def fetch_images(url):
14
+ options = Options()
15
+ options.add_argument("--headless")
16
+ options.add_argument("window-size=1400,1500")
17
+ options.add_argument("--disable-gpu")
18
+ options.add_argument("--no-sandbox")
19
+ options.add_argument("start-maximized")
20
+ options.add_argument("enable-automation")
21
+ options.add_argument("--disable-infobars")
22
+ options.add_argument("--disable-dev-shm-usage")
23
+ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
24
+ options.add_argument(f"user-agent={user_agent}")
25
+
26
+ driver = webdriver.Chrome(options=options)
27
+ driver.set_window_size(1400, 1500)
28
+ driver.get(url)
29
+ time.sleep(5)
30
+ last_height = driver.execute_script("return document.scrollingElement.scrollHeight")
31
+ urls = []
32
+ while True :
33
+ # img_elements = driver.find_elements(By.CLASS_NAME, cls_name)
34
+ img_elements = driver.find_elements(By.TAG_NAME, 'img')
35
+ for img in img_elements:
36
+ urls.append(img.get_attribute('src') or img.get_attribute('data-src'))
37
+ driver.execute_script(f"document.scrollingElement.scrollTo(0, document.scrollingElement.scrollHeight);")
38
+ time.sleep(5)
39
+ new_height = driver.execute_script("return document.scrollingElement.scrollHeight")
40
+ print(f"last_height: {last_height}, new_height: {new_height}")
41
+ if new_height == last_height:
42
+ break
43
+
44
+ last_height = new_height
45
+
46
+ print(f"Total images: {len(urls)}")
47
+
48
+ return urls
49
+
50
+
51
+ # Function to download images
52
+ def download_images(img_urls, download_folder='downloaded_images', desc=""):
53
+ if not os.path.exists(download_folder):
54
+ os.makedirs(download_folder)
55
+ headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
56
+
57
+ for img_url in tqdm(img_urls, desc=desc):
58
+ fname = img_url.split('/')[-1]
59
+ fname = fname.split('?')[0]
60
+ filename = os.path.join(download_folder, fname)
61
+ if os.path.exists(filename):
62
+ continue
63
+ req = urllib.request.Request(img_url, headers=headers)
64
+ with urllib.request.urlopen(req) as response, open(filename, 'wb') as out_file:
65
+ data = response.read()
66
+ out_file.write(data)
67
+
68
+
69
+
70
+ def crawl(query):
71
+ url = f'https://openart.ai/search/{query}?method=similarity'
72
+ download_path = "/truemedia-eval/crawled-fakes/images/fakes"
73
+ try:
74
+ img_urls = fetch_images(url)
75
+ if len(img_urls) == 0:
76
+ return
77
+ download_images(img_urls, download_path, desc=f"query: {query}")
78
+ except:
79
+ return
80
+
81
+ # Main function to coordinate the image crawling
82
+ def main():
83
+ # queries = ['xi', 'trump', 'biden', 'putin', 'zelensky', 'gaza', 'israel', 'taylor', 'palesti', 'nsfw', 'instagram']
84
+ queries = ['xi', 'trump', 'biden', 'putin', 'zelensky', 'gaza', 'israel', 'taylor', 'palesti', 'nsfw', 'instagram',
85
+ "Hamas", "Hezbollah", "Iran",
86
+ "North Korea", "Kim Jong-un", "Uyghurs", "Hong Kong", "Taiwan", "Tibet", "Kashmir", "Syria", "Assad", "ISIS",
87
+ "Taliban", "Afghanistan", "Saudi", "Yemen", "Qatar", "Brexit", "Catalonia", "Black lives matter", "Antifa", "Proud Boys",
88
+ "Abortion", "Guns", "Second Amendment", "Police", "Execution", "Drugs", "Opioids", "Climate", "Paris",
89
+ "Green", "Keystone", "Fracking", "GMOs", "Net", "WikiLeaks", "Assange", "Snowden", "NSA", "Patriot",
90
+ "COVID", "Vaccines", "Masks", "5G", "QAnon", "Fraud", "Capitol", "Impeachment", "Hunter", "Epstein",
91
+ "Trafficking", "MeToo", "Weinstein", "Cancel", "Race", "Affirmative", "Transgender", "Marriage",
92
+ "Religion", "Nationalism", "Neo-Nazism", "Confederate", "Antisemitism", "Islamophobia", "Wall", "ICE",
93
+ "DACA", "Dreamers", "Separation", "Sanctuary", "Refugees", "Travel", "Benghazi", "Emails", "Russia",
94
+ "Mueller", "Ukraine", "Mar-a-Lago", "Taxes", "Emoluments", "Gerrymandering", "Voter", "Mail", "Citizens",
95
+ "PACs", "Breonna", "Floyd", "Rittenhouse", "Insurrection", "Ivanka", "Kushner", "Bannon", "Flynn", "Stone"
96
+ ]
97
+
98
+ for query in queries:
99
+ crawl(query)
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
deploy_utils/down.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from tqdm.auto import tqdm
3
+ import subprocess
4
+ import os.path as osp
5
+
6
+ df = pd.read_csv('/home/ubuntu/y1/truemedia.csv')
7
+ for i in tqdm(range(len(df))):
8
+ line = df.iloc[i]
9
+ ID = line['Id']
10
+ fake = 'fake' in line['Ground Truth'].lower()
11
+ if osp.exists(f'/truemedia-eval/images/fakes/{ID}') or osp.exists(f'/truemedia-eval/images/reals/{ID}'):
12
+ continue
13
+ if fake:
14
+ subprocess.run(f"aws s3 cp s3://truemedia-media/{ID} /truemedia-eval/images/fakes/{ID}", shell=True)
15
+ else:
16
+ subprocess.run(f"aws s3 cp s3://truemedia-media/{ID} /truemedia-eval/images/reals/{ID}", shell=True)
deploy_utils/instaimages_format.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from shutil import copy
2
+ from glob import glob
3
+ from PIL import Image
4
+ from tqdm.auto import tqdm
5
+ import os
6
+
7
+ os.makedirs("/truemedia-eval/instagram/images/reals", exist_ok=True)
8
+ files = glob("/truemedia-eval/instagram/**/*.jpg", recursive=True)
9
+ for f in tqdm(files):
10
+ try:
11
+ img = Image.open(f)
12
+ except:
13
+ continue
14
+ size = img.size
15
+ if max(size) > 2000:
16
+ continue
17
+ fname = f.split("/")[-1]
18
+ copy(f, f"/truemedia-eval/instagram/images/reals/{fname}")
distil.png ADDED
guided_diffusion/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 OpenAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
guided_diffusion/README.md ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # guided-diffusion
2
+
3
+ This is the codebase for [Diffusion Models Beat GANS on Image Synthesis](http://arxiv.org/abs/2105.05233).
4
+
5
+ This repository is based on [openai/improved-diffusion](https://github.com/openai/improved-diffusion), with modifications for classifier conditioning and architecture improvements.
6
+
7
+ # Download pre-trained models
8
+
9
+ We have released checkpoints for the main models in the paper. Before using these models, please review the corresponding [model card](model-card.md) to understand the intended use and limitations of these models.
10
+
11
+ Here are the download links for each model checkpoint:
12
+
13
+ * 64x64 classifier: [64x64_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64x64_classifier.pt)
14
+ * 64x64 diffusion: [64x64_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64x64_diffusion.pt)
15
+ * 128x128 classifier: [128x128_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128x128_classifier.pt)
16
+ * 128x128 diffusion: [128x128_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128x128_diffusion.pt)
17
+ * 256x256 classifier: [256x256_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_classifier.pt)
18
+ * 256x256 diffusion: [256x256_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion.pt)
19
+ * 256x256 diffusion (not class conditional): [256x256_diffusion_uncond.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt)
20
+ * 512x512 classifier: [512x512_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/512x512_classifier.pt)
21
+ * 512x512 diffusion: [512x512_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/512x512_diffusion.pt)
22
+ * 64x64 -&gt; 256x256 upsampler: [64_256_upsampler.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64_256_upsampler.pt)
23
+ * 128x128 -&gt; 512x512 upsampler: [128_512_upsampler.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128_512_upsampler.pt)
24
+ * LSUN bedroom: [lsun_bedroom.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_bedroom.pt)
25
+ * LSUN cat: [lsun_cat.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_cat.pt)
26
+ * LSUN horse: [lsun_horse.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_horse.pt)
27
+ * LSUN horse (no dropout): [lsun_horse_nodropout.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_horse_nodropout.pt)
28
+
29
+ # Sampling from pre-trained models
30
+
31
+ To sample from these models, you can use the `classifier_sample.py`, `image_sample.py`, and `super_res_sample.py` scripts.
32
+ Here, we provide flags for sampling from all of these models.
33
+ We assume that you have downloaded the relevant model checkpoints into a folder called `models/`.
34
+
35
+ For these examples, we will generate 100 samples with batch size 4. Feel free to change these values.
36
+
37
+ ```
38
+ SAMPLE_FLAGS="--batch_size 4 --num_samples 100 --timestep_respacing 250"
39
+ ```
40
+
41
+ ## Classifier guidance
42
+
43
+ Note for these sampling runs that you can set `--classifier_scale 0` to sample from the base diffusion model.
44
+ You may also use the `image_sample.py` script instead of `classifier_sample.py` in that case.
45
+
46
+ * 64x64 model:
47
+
48
+ ```
49
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --dropout 0.1 --image_size 64 --learn_sigma True --noise_schedule cosine --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --resblock_updown True --use_new_attention_order True --use_fp16 True --use_scale_shift_norm True"
50
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 1.0 --classifier_path models/64x64_classifier.pt --classifier_depth 4 --model_path models/64x64_diffusion.pt $SAMPLE_FLAGS
51
+ ```
52
+
53
+ * 128x128 model:
54
+
55
+ ```
56
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 128 --learn_sigma True --noise_schedule linear --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
57
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 0.5 --classifier_path models/128x128_classifier.pt --model_path models/128x128_diffusion.pt $SAMPLE_FLAGS
58
+ ```
59
+
60
+ * 256x256 model:
61
+
62
+ ```
63
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
64
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 1.0 --classifier_path models/256x256_classifier.pt --model_path models/256x256_diffusion.pt $SAMPLE_FLAGS
65
+ ```
66
+
67
+ * 256x256 model (unconditional):
68
+
69
+ ```
70
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
71
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 10.0 --classifier_path models/256x256_classifier.pt --model_path models/256x256_diffusion_uncond.pt $SAMPLE_FLAGS
72
+ ```
73
+
74
+ * 512x512 model:
75
+
76
+ ```
77
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 512 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 False --use_scale_shift_norm True"
78
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 4.0 --classifier_path models/512x512_classifier.pt --model_path models/512x512_diffusion.pt $SAMPLE_FLAGS
79
+ ```
80
+
81
+ ## Upsampling
82
+
83
+ For these runs, we assume you have some base samples in a file `64_samples.npz` or `128_samples.npz` for the two respective models.
84
+
85
+ * 64 -&gt; 256:
86
+
87
+ ```
88
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --large_size 256 --small_size 64 --learn_sigma True --noise_schedule linear --num_channels 192 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
89
+ python super_res_sample.py $MODEL_FLAGS --model_path models/64_256_upsampler.pt --base_samples 64_samples.npz $SAMPLE_FLAGS
90
+ ```
91
+
92
+ * 128 -&gt; 512:
93
+
94
+ ```
95
+ MODEL_FLAGS="--attention_resolutions 32,16 --class_cond True --diffusion_steps 1000 --large_size 512 --small_size 128 --learn_sigma True --noise_schedule linear --num_channels 192 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
96
+ python super_res_sample.py $MODEL_FLAGS --model_path models/128_512_upsampler.pt $SAMPLE_FLAGS --base_samples 128_samples.npz
97
+ ```
98
+
99
+ ## LSUN models
100
+
101
+ These models are class-unconditional and correspond to a single LSUN class. Here, we show how to sample from `lsun_bedroom.pt`, but the other two LSUN checkpoints should work as well:
102
+
103
+ ```
104
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --dropout 0.1 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
105
+ python image_sample.py $MODEL_FLAGS --model_path models/lsun_bedroom.pt $SAMPLE_FLAGS
106
+ ```
107
+
108
+ You can sample from `lsun_horse_nodropout.pt` by changing the dropout flag:
109
+
110
+ ```
111
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --dropout 0.0 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
112
+ python image_sample.py $MODEL_FLAGS --model_path models/lsun_horse_nodropout.pt $SAMPLE_FLAGS
113
+ ```
114
+
115
+ Note that for these models, the best samples result from using 1000 timesteps:
116
+
117
+ ```
118
+ SAMPLE_FLAGS="--batch_size 4 --num_samples 100 --timestep_respacing 1000"
119
+ ```
120
+
121
+ # Results
122
+
123
+ This table summarizes our ImageNet results for pure guided diffusion models:
124
+
125
+ | Dataset | FID | Precision | Recall |
126
+ |------------------|------|-----------|--------|
127
+ | ImageNet 64x64 | 2.07 | 0.74 | 0.63 |
128
+ | ImageNet 128x128 | 2.97 | 0.78 | 0.59 |
129
+ | ImageNet 256x256 | 4.59 | 0.82 | 0.52 |
130
+ | ImageNet 512x512 | 7.72 | 0.87 | 0.42 |
131
+
132
+ This table shows the best results for high resolutions when using upsampling and guidance together:
133
+
134
+ | Dataset | FID | Precision | Recall |
135
+ |------------------|------|-----------|--------|
136
+ | ImageNet 256x256 | 3.94 | 0.83 | 0.53 |
137
+ | ImageNet 512x512 | 3.85 | 0.84 | 0.53 |
138
+
139
+ Finally, here are the unguided results on individual LSUN classes:
140
+
141
+ | Dataset | FID | Precision | Recall |
142
+ |--------------|------|-----------|--------|
143
+ | LSUN Bedroom | 1.90 | 0.66 | 0.51 |
144
+ | LSUN Cat | 5.57 | 0.63 | 0.52 |
145
+ | LSUN Horse | 2.57 | 0.71 | 0.55 |
146
+
147
+ # Training models
148
+
149
+ Training diffusion models is described in the [parent repository](https://github.com/openai/improved-diffusion). Training a classifier is similar. We assume you have put training hyperparameters into a `TRAIN_FLAGS` variable, and classifier hyperparameters into a `CLASSIFIER_FLAGS` variable. Then you can run:
150
+
151
+ ```
152
+ mpiexec -n N python scripts/classifier_train.py --data_dir path/to/imagenet $TRAIN_FLAGS $CLASSIFIER_FLAGS
153
+ ```
154
+
155
+ Make sure to divide the batch size in `TRAIN_FLAGS` by the number of MPI processes you are using.
156
+
157
+ Here are flags for training the 128x128 classifier. You can modify these for training classifiers at other resolutions:
158
+
159
+ ```sh
160
+ TRAIN_FLAGS="--iterations 300000 --anneal_lr True --batch_size 256 --lr 3e-4 --save_interval 10000 --weight_decay 0.05"
161
+ CLASSIFIER_FLAGS="--image_size 128 --classifier_attention_resolutions 32,16,8 --classifier_depth 2 --classifier_width 128 --classifier_pool attention --classifier_resblock_updown True --classifier_use_scale_shift_norm True"
162
+ ```
163
+
164
+ For sampling from a 128x128 classifier-guided model, 25 step DDIM:
165
+
166
+ ```sh
167
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --image_size 128 --learn_sigma True --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
168
+ CLASSIFIER_FLAGS="--image_size 128 --classifier_attention_resolutions 32,16,8 --classifier_depth 2 --classifier_width 128 --classifier_pool attention --classifier_resblock_updown True --classifier_use_scale_shift_norm True --classifier_scale 1.0 --classifier_use_fp16 True"
169
+ SAMPLE_FLAGS="--batch_size 4 --num_samples 50000 --timestep_respacing ddim25 --use_ddim True"
170
+ mpiexec -n N python scripts/classifier_sample.py \
171
+ --model_path /path/to/model.pt \
172
+ --classifier_path path/to/classifier.pt \
173
+ $MODEL_FLAGS $CLASSIFIER_FLAGS $SAMPLE_FLAGS
174
+ ```
175
+
176
+ To sample for 250 timesteps without DDIM, replace `--timestep_respacing ddim25` to `--timestep_respacing 250`, and replace `--use_ddim True` with `--use_ddim False`.
guided_diffusion/compute_dire_eps.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Modified from guided-diffusion/scripts/image_sample.py
3
+ """
4
+
5
+ import argparse
6
+ import os
7
+ import torch
8
+ from PIL import ImageFile
9
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
10
+ from dataset import TMDistilDireDataset
11
+ from torch.utils.data import DataLoader
12
+ import cv2
13
+
14
+ import torch.nn.functional as F
15
+ import torchvision.transforms as transforms
16
+ from tqdm.auto import tqdm
17
+
18
+ import numpy as np
19
+ import torch as th
20
+ import torchvision
21
+ import os.path as osp
22
+
23
+
24
+ from .guided_diffusion.script_util import (
25
+ NUM_CLASSES,
26
+ model_and_diffusion_defaults,
27
+ create_model_and_diffusion,
28
+ add_dict_to_argparser,
29
+ dict_parse,
30
+ args_to_dict,
31
+
32
+ )
33
+
34
+
35
+
36
+ def reshape_image(imgs: torch.Tensor, image_size: int) -> torch.Tensor:
37
+ if len(imgs.shape) == 3:
38
+ imgs = imgs.unsqueeze(0)
39
+ if imgs.shape[2] != imgs.shape[3]:
40
+ crop_func = transforms.CenterCrop(image_size)
41
+ imgs = crop_func(imgs)
42
+ if imgs.shape[2] != image_size:
43
+ imgs = F.interpolate(imgs, size=(image_size, image_size), mode="bicubic", antialias=True)
44
+ return imgs
45
+
46
+
47
+
48
+ def create_argparser():
49
+ defaults = dict(
50
+ clip_denoised=True,
51
+ num_samples=-1,
52
+ use_ddim=True,
53
+ real_step=0,
54
+ continue_reverse=False,
55
+ has_subfolder=False,
56
+ )
57
+ defaults.update(model_and_diffusion_defaults())
58
+ sanic_dict = dict(
59
+ attention_resolutions='32,16,8',
60
+ class_cond=False,
61
+ diffusion_steps=1000,
62
+ image_size=256,
63
+ learn_sigma=True,
64
+ model_path="./models/256x256-adm.pt",
65
+ noise_schedule='linear',
66
+ num_channels=256,
67
+ num_head_channels=64,
68
+ num_res_blocks=2,
69
+ resblock_updown=True,
70
+ use_fp16=True,
71
+ use_scale_shift_norm=True,
72
+ data_root="",
73
+ compute_dire=False,
74
+ compute_eps=False,
75
+ save_root="",
76
+ batch_size=32,
77
+ )
78
+ defaults.update(sanic_dict)
79
+ parser = argparse.ArgumentParser()
80
+ add_dict_to_argparser(parser, defaults)
81
+ args = parser.parse_args()
82
+
83
+ return args_to_dict(args, list(defaults.keys()))
84
+
85
+ def create_dicts_for_static_init():
86
+ defaults = dict(
87
+ clip_denoised=True,
88
+ num_samples=-1,
89
+ use_ddim=True,
90
+ real_step=0,
91
+ continue_reverse=False,
92
+ has_subfolder=False,
93
+ )
94
+ defaults.update(model_and_diffusion_defaults())
95
+ sanic_dict = dict(
96
+ attention_resolutions='32,16,8',
97
+ class_cond=False,
98
+ diffusion_steps=1000,
99
+ image_size=256,
100
+ learn_sigma=True,
101
+ model_path="./models/256x256-adm.pt",
102
+ noise_schedule='linear',
103
+ num_channels=256,
104
+ num_head_channels=64,
105
+ num_res_blocks=2,
106
+ resblock_updown=True,
107
+ use_fp16=True,
108
+ use_scale_shift_norm=True,
109
+ data_root="",
110
+ compute_dire=False,
111
+ compute_eps=False,
112
+ save_root="",
113
+ batch_size=32,
114
+ )
115
+ defaults.update(sanic_dict)
116
+
117
+ return defaults
118
+
119
+
120
+
121
+ @torch.no_grad()
122
+ def dire(img_batch:torch.Tensor, model, diffusion, args, save_img=False, save_path=None):
123
+ print("computing recons & DIRE ...")
124
+ imgs = img_batch.cuda()
125
+
126
+ batch_size = imgs.shape[0]
127
+ model_kwargs = {}
128
+
129
+ reverse_fn = diffusion.ddim_reverse_sample_loop
130
+ assert (imgs.shape[2] == imgs.shape[3]) and (imgs.shape[3] == args['image_size']), f"Image size mismatch: {imgs.shape[2]} != {args['image_size']}"
131
+ latent = reverse_fn(
132
+ model,
133
+ (batch_size, 3, args['image_size'], args['image_size']),
134
+ noise=imgs,
135
+ clip_denoised=args['clip_denoised'],
136
+ model_kwargs=model_kwargs,
137
+ real_step=args['real_step'],
138
+ )
139
+ sample_fn = diffusion.p_sample_loop if not args['use_ddim'] else diffusion.ddim_sample_loop
140
+ recons = sample_fn(
141
+ model,
142
+ (batch_size, 3, args['image_size'], args['image_size']),
143
+ noise=latent,
144
+ clip_denoised=args['clip_denoised'],
145
+ model_kwargs=model_kwargs,
146
+ real_step=args['real_step']
147
+ )
148
+
149
+ dire = th.abs(imgs - recons)
150
+ dire = (dire*255./2).clamp(0, 255).to(th.uint8)
151
+ dire = dire.contiguous() / 255.
152
+ dire = (dire).clamp(0, 1).to(th.float32)
153
+
154
+ # scale imgs and recons
155
+ imgs = (imgs+1)*0.5
156
+ recons = (recons+1)*0.5
157
+
158
+ if save_img:
159
+ # save images
160
+ for i in range(len(img_batch)):
161
+ dire_img = dire[i].detach().cpu().numpy().transpose(1, 2, 0)
162
+ dire_img = cv2.cvtColor(dire_img, cv2.COLOR_RGB2BGR)
163
+
164
+ dire_path = os.path.join(save_path, f"dire_{i}.png")
165
+ cv2.imwrite(dire_path, dire_img*255)
166
+
167
+ return dire, imgs, recons
168
+
169
+ @torch.no_grad()
170
+ def dire_get_first_step_noise(img_batch:torch.Tensor, model, diffusion, args, device):
171
+ imgs = img_batch.to(device)
172
+ batch_size = imgs.shape[0]
173
+ model_kwargs = {}
174
+
175
+ reverse_fn = diffusion.ddim_reverse_sample_only_eps
176
+ assert (imgs.shape[2] == imgs.shape[3]) and (imgs.shape[3] == args['image_size']), f"Image size mismatch: {imgs.shape[2]} != {args['image_size']}"
177
+
178
+ eps = reverse_fn(
179
+ model,
180
+ # (batch_size, 3, args['image_size'], args['image_size']),
181
+ x=imgs,
182
+ t=torch.zeros(imgs.shape[0],).long().to(device),
183
+ clip_denoised=args['clip_denoised'],
184
+ model_kwargs=model_kwargs,
185
+ eta=0.0
186
+ #real_step=args['real_step'],
187
+ )
188
+
189
+ return eps
190
+
191
+
192
+ if __name__ == "__main__":
193
+ from torch.utils.data.distributed import DistributedSampler
194
+ import torch.distributed as dist
195
+ import os
196
+
197
+ dist.init_process_group(backend='nccl', init_method='env://')
198
+
199
+ local_rank = int(os.environ['LOCAL_RANK'])
200
+ torch.cuda.set_device(local_rank)
201
+
202
+ # Set device for this process
203
+ device = torch.device("cuda")
204
+
205
+ adm_args = create_argparser()
206
+ adm_args['timestep_respacing'] = 'ddim20'
207
+ adm_model, diffusion = create_model_and_diffusion(**dict_parse(adm_args, model_and_diffusion_defaults().keys()))
208
+ print(f"checkpoint: {adm_args['model_path']}")
209
+ print(f"model channel: {adm_args['num_channels']}, {adm_model.model_channels}")
210
+ adm_model.load_state_dict(torch.load(adm_args['model_path'], map_location="cpu"))
211
+ adm_model.to(device)
212
+
213
+ adm_model.convert_to_fp16()
214
+ adm_model.eval()
215
+
216
+ dataset = TMDistilDireDataset(adm_args['data_root'], prepared_dire=False)
217
+ sampler = DistributedSampler(dataset, shuffle=False)
218
+ os.makedirs(osp.join(adm_args['save_root'], 'images', 'fakes'), exist_ok=True)
219
+ os.makedirs(osp.join(adm_args['save_root'], 'images', 'reals'), exist_ok=True)
220
+ os.makedirs(osp.join(adm_args['save_root'], 'dire', 'fakes'), exist_ok=True)
221
+ os.makedirs(osp.join(adm_args['save_root'], 'dire', 'reals'), exist_ok=True)
222
+ os.makedirs(osp.join(adm_args['save_root'], 'eps', 'fakes'), exist_ok=True)
223
+ os.makedirs(osp.join(adm_args['save_root'], 'eps', 'reals'), exist_ok=True)
224
+ print(f"Dataset length: {len(dataset)}")
225
+ dataloader = DataLoader(dataset, batch_size=adm_args['batch_size'], num_workers=4, drop_last=False, pin_memory=True, sampler=sampler)#
226
+
227
+ for (img_batch, dire_batch, eps_batch, isfake_batch), (img_pathes, dire_pathes, eps_pathes) in tqdm(dataloader):
228
+ haveall=True
229
+ for i in range(len(img_batch)):
230
+ basename = osp.basename(img_pathes[i])
231
+ isfake = isfake_batch[i]
232
+
233
+ img_path = osp.join(adm_args['save_root'], 'images', 'fakes', basename) if isfake else osp.join(adm_args['save_root'], 'images', 'reals', basename)
234
+ dire_path = img_path.replace('/images/', '/dire/')
235
+ eps_path = img_path.replace('/images/', '/eps/').split('.')[0] + '.pt'
236
+ if (not osp.exists(img_pathes[i])) or (not osp.exists(dire_path)) or (not osp.exists(eps_path)):
237
+ haveall=False
238
+ break
239
+ if haveall:
240
+ continue
241
+ with torch.no_grad():
242
+ eps = None
243
+ img = (img_batch.detach().cpu()+1)*0.5
244
+ if adm_args['compute_eps']:
245
+ eps = dire_get_first_step_noise(img_batch, adm_model, diffusion, adm_args, device)
246
+ eps = eps.detach().cpu()
247
+
248
+ if adm_args['compute_dire']:
249
+ dire_img, img, recons = dire(img_batch, adm_model, diffusion, adm_args)
250
+ dire_img = dire_img.detach().cpu()
251
+ img = img.detach().cpu()
252
+
253
+ for i in range(len(img_batch)):
254
+ basename = osp.basename(img_pathes[i])
255
+ isfake = isfake_batch[i]
256
+
257
+ img_path = osp.join(adm_args['save_root'], 'images', 'fakes', basename) if isfake else osp.join(adm_args['save_root'], 'images', 'reals', basename)
258
+ dire_path = img_path.replace('/images/', '/dire/')
259
+ eps_path = img_path.replace('/images/', '/eps/').split('.')[0] + '.pt'
260
+
261
+ if not osp.exists(img_path):
262
+ torchvision.utils.save_image(img[i], img_path)
263
+ if not osp.exists(dire_path) and adm_args['compute_dire']:
264
+ torchvision.utils.save_image(dire_img[i], dire_path)
265
+ if not osp.exists(eps_path) and eps is not None:
266
+ torch.save(eps[i], eps_path)
guided_diffusion/guided_diffusion/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Codebase for "Improved Denoising Diffusion Probabilistic Models".
3
+ """
guided_diffusion/guided_diffusion/dist_util.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from . import logger
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(devices=""):
22
+ """
23
+ Setup a distributed process group.
24
+ """
25
+ if dist.is_initialized():
26
+ return
27
+ devices_list = []
28
+ for device in devices.split(","):
29
+ devices_list.append(int(device))
30
+ # print(devices_list)
31
+ GPUS_PER_NODE = len(devices_list)
32
+ # print("GPUS_PER_NODE: ",GPUS_PER_NODE)
33
+ os.environ["CUDA_VISIBLE_DEVICES"] = f"{devices_list[MPI.COMM_WORLD.Get_rank() % GPUS_PER_NODE]}"
34
+ # print(f"rank: {MPI.COMM_WORLD.Get_rank()}, {os.environ['CUDA_VISIBLE_DEVICES']}")
35
+ comm = MPI.COMM_WORLD
36
+ backend = "gloo" if not th.cuda.is_available() else "nccl"
37
+
38
+ if backend == "gloo":
39
+ hostname = "localhost"
40
+ else:
41
+ hostname = socket.gethostbyname(socket.getfqdn())
42
+ os.environ["MASTER_ADDR"] = comm.bcast(hostname, root=0)
43
+ os.environ["RANK"] = str(comm.rank)
44
+ os.environ["WORLD_SIZE"] = str(comm.size)
45
+
46
+ port = comm.bcast(_find_free_port(), root=0)
47
+ os.environ["MASTER_PORT"] = str(port)
48
+ dist.init_process_group(backend=backend, init_method="env://")
49
+
50
+
51
+ def dev():
52
+ """
53
+ Get the device to use for torch.distributed.
54
+ """
55
+ if th.cuda.is_available():
56
+ return th.device(f"cuda")
57
+ return th.device("cpu")
58
+
59
+
60
+ def load_state_dict(path, **kwargs):
61
+ """
62
+ Load a PyTorch file without redundant fetches across MPI ranks.
63
+ """
64
+ chunk_size = 2 ** 30 # MPI has a relatively small size limit
65
+ if MPI.COMM_WORLD.Get_rank() == 0:
66
+ with bf.BlobFile(path, "rb") as f:
67
+ data = f.read()
68
+ num_chunks = len(data) // chunk_size
69
+ if len(data) % chunk_size:
70
+ num_chunks += 1
71
+ MPI.COMM_WORLD.bcast(num_chunks)
72
+ for i in range(0, len(data), chunk_size):
73
+ MPI.COMM_WORLD.bcast(data[i : i + chunk_size])
74
+ else:
75
+ num_chunks = MPI.COMM_WORLD.bcast(None)
76
+ data = bytes()
77
+ for _ in range(num_chunks):
78
+ data += MPI.COMM_WORLD.bcast(None)
79
+
80
+ return th.load(io.BytesIO(data), **kwargs)
81
+
82
+
83
+ def sync_params(params):
84
+ """
85
+ Synchronize a sequence of Tensors across ranks from rank 0.
86
+ """
87
+ for p in params:
88
+ with th.no_grad():
89
+ dist.broadcast(p, 0)
90
+
91
+
92
+ def _find_free_port():
93
+ try:
94
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
95
+ s.bind(("", 0))
96
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
97
+ return s.getsockname()[1]
98
+ finally:
99
+ s.close()
guided_diffusion/guided_diffusion/fp16_util.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ for p in self.master_params:
203
+ p.grad.mul_(1.0 / (2 ** self.lg_loss_scale))
204
+ opt.step()
205
+ zero_master_grads(self.master_params)
206
+ master_params_to_model_params(self.param_groups_and_shapes, self.master_params)
207
+ self.lg_loss_scale += self.fp16_scale_growth
208
+ return True
209
+
210
+ def _optimize_normal(self, opt: th.optim.Optimizer):
211
+ grad_norm, param_norm = self._compute_norms()
212
+ logger.logkv_mean("grad_norm", grad_norm)
213
+ logger.logkv_mean("param_norm", param_norm)
214
+ opt.step()
215
+ return True
216
+
217
+ def _compute_norms(self, grad_scale=1.0):
218
+ grad_norm = 0.0
219
+ param_norm = 0.0
220
+ for p in self.master_params:
221
+ with th.no_grad():
222
+ param_norm += th.norm(p, p=2, dtype=th.float32).item() ** 2
223
+ if p.grad is not None:
224
+ grad_norm += th.norm(p.grad, p=2, dtype=th.float32).item() ** 2
225
+ return np.sqrt(grad_norm) / grad_scale, np.sqrt(param_norm)
226
+
227
+ def master_params_to_state_dict(self, master_params):
228
+ return master_params_to_state_dict(
229
+ self.model, self.param_groups_and_shapes, master_params, self.use_fp16
230
+ )
231
+
232
+ def state_dict_to_master_params(self, state_dict):
233
+ return state_dict_to_master_params(self.model, state_dict, self.use_fp16)
234
+
235
+
236
+ def check_overflow(value):
237
+ return (value == float("inf")) or (value == -float("inf")) or (value != value)
guided_diffusion/guided_diffusion/gaussian_diffusion.py ADDED
@@ -0,0 +1,1038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code started out as a PyTorch port of Ho et al's diffusion models:
3
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py
4
+
5
+ Docstrings have been added, as well as DDIM sampling and a new collection of beta schedules.
6
+ """
7
+
8
+ import enum
9
+ import math
10
+
11
+ import numpy as np
12
+ import torch as th
13
+
14
+ from .nn import mean_flat
15
+ from .losses import normal_kl, discretized_gaussian_log_likelihood
16
+
17
+
18
+ def get_named_beta_schedule(schedule_name, num_diffusion_timesteps):
19
+ """
20
+ Get a pre-defined beta schedule for the given name.
21
+
22
+ The beta schedule library consists of beta schedules which remain similar
23
+ in the limit of num_diffusion_timesteps.
24
+ Beta schedules may be added, but should not be removed or changed once
25
+ they are committed to maintain backwards compatibility.
26
+ """
27
+ if schedule_name == "linear":
28
+ # Linear schedule from Ho et al, extended to work for any number of
29
+ # diffusion steps.
30
+ scale = 1000 / num_diffusion_timesteps
31
+ beta_start = scale * 0.0001
32
+ beta_end = scale * 0.02
33
+ return np.linspace(
34
+ beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64
35
+ )
36
+ elif schedule_name == "cosine":
37
+ return betas_for_alpha_bar(
38
+ num_diffusion_timesteps,
39
+ lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
40
+ )
41
+ else:
42
+ raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
43
+
44
+
45
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
46
+ """
47
+ Create a beta schedule that discretizes the given alpha_t_bar function,
48
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
49
+
50
+ :param num_diffusion_timesteps: the number of betas to produce.
51
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
52
+ produces the cumulative product of (1-beta) up to that
53
+ part of the diffusion process.
54
+ :param max_beta: the maximum beta to use; use values lower than 1 to
55
+ prevent singularities.
56
+ """
57
+ betas = []
58
+ for i in range(num_diffusion_timesteps):
59
+ t1 = i / num_diffusion_timesteps
60
+ t2 = (i + 1) / num_diffusion_timesteps
61
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
62
+ return np.array(betas)
63
+
64
+
65
+ class ModelMeanType(enum.Enum):
66
+ """
67
+ Which type of output the model predicts.
68
+ """
69
+
70
+ PREVIOUS_X = enum.auto() # the model predicts x_{t-1}
71
+ START_X = enum.auto() # the model predicts x_0
72
+ EPSILON = enum.auto() # the model predicts epsilon
73
+
74
+
75
+ class ModelVarType(enum.Enum):
76
+ """
77
+ What is used as the model's output variance.
78
+
79
+ The LEARNED_RANGE option has been added to allow the model to predict
80
+ values between FIXED_SMALL and FIXED_LARGE, making its job easier.
81
+ """
82
+
83
+ LEARNED = enum.auto()
84
+ FIXED_SMALL = enum.auto()
85
+ FIXED_LARGE = enum.auto()
86
+ LEARNED_RANGE = enum.auto()
87
+
88
+
89
+ class LossType(enum.Enum):
90
+ MSE = enum.auto() # use raw MSE loss (and KL when learning variances)
91
+ RESCALED_MSE = (
92
+ enum.auto()
93
+ ) # use raw MSE loss (with RESCALED_KL when learning variances)
94
+ KL = enum.auto() # use the variational lower-bound
95
+ RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB
96
+
97
+ def is_vb(self):
98
+ return self == LossType.KL or self == LossType.RESCALED_KL
99
+
100
+
101
+ class GaussianDiffusion:
102
+ """
103
+ Utilities for training and sampling diffusion models.
104
+
105
+ Ported directly from here, and then adapted over time to further experimentation.
106
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42
107
+
108
+ :param betas: a 1-D numpy array of betas for each diffusion timestep,
109
+ starting at T and going to 1.
110
+ :param model_mean_type: a ModelMeanType determining what the model outputs.
111
+ :param model_var_type: a ModelVarType determining how variance is output.
112
+ :param loss_type: a LossType determining the loss function to use.
113
+ :param rescale_timesteps: if True, pass floating point timesteps into the
114
+ model so that they are always scaled like in the
115
+ original paper (0 to 1000).
116
+ """
117
+
118
+ def __init__(
119
+ self,
120
+ *,
121
+ betas,
122
+ model_mean_type,
123
+ model_var_type,
124
+ loss_type,
125
+ rescale_timesteps=False,
126
+ ):
127
+ self.model_mean_type = model_mean_type
128
+ self.model_var_type = model_var_type
129
+ self.loss_type = loss_type
130
+ self.rescale_timesteps = rescale_timesteps
131
+
132
+ # Use float64 for accuracy.
133
+ betas = np.array(betas, dtype=np.float64)
134
+ self.betas = betas
135
+ assert len(betas.shape) == 1, "betas must be 1-D"
136
+ assert (betas > 0).all() and (betas <= 1).all()
137
+
138
+ self.num_timesteps = int(betas.shape[0])
139
+
140
+ alphas = 1.0 - betas
141
+ self.alphas_cumprod = np.cumprod(alphas, axis=0)
142
+ self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1])
143
+ self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0)
144
+ assert self.alphas_cumprod_prev.shape == (self.num_timesteps,)
145
+
146
+ # calculations for diffusion q(x_t | x_{t-1}) and others
147
+ self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod)
148
+ self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod)
149
+ self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod)
150
+ self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod)
151
+ self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1)
152
+
153
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
154
+ self.posterior_variance = (
155
+ betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
156
+ )
157
+ # log calculation clipped because the posterior variance is 0 at the
158
+ # beginning of the diffusion chain.
159
+ self.posterior_log_variance_clipped = np.log(
160
+ np.append(self.posterior_variance[1], self.posterior_variance[1:])
161
+ )
162
+ self.posterior_mean_coef1 = (
163
+ betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
164
+ )
165
+ self.posterior_mean_coef2 = (
166
+ (1.0 - self.alphas_cumprod_prev)
167
+ * np.sqrt(alphas)
168
+ / (1.0 - self.alphas_cumprod)
169
+ )
170
+
171
+ def q_mean_variance(self, x_start, t):
172
+ """
173
+ Get the distribution q(x_t | x_0).
174
+
175
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
176
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
177
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
178
+ """
179
+ mean = (
180
+ _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
181
+ )
182
+ variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
183
+ log_variance = _extract_into_tensor(
184
+ self.log_one_minus_alphas_cumprod, t, x_start.shape
185
+ )
186
+ return mean, variance, log_variance
187
+
188
+ def q_sample(self, x_start, t, noise=None):
189
+ """
190
+ Diffuse the data for a given number of diffusion steps.
191
+
192
+ In other words, sample from q(x_t | x_0).
193
+
194
+ :param x_start: the initial data batch.
195
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
196
+ :param noise: if specified, the split-out normal noise.
197
+ :return: A noisy version of x_start.
198
+ """
199
+ if noise is None:
200
+ noise = th.randn_like(x_start)
201
+ assert noise.shape == x_start.shape
202
+ return (
203
+ _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
204
+ + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
205
+ * noise
206
+ )
207
+
208
+ def q_posterior_mean_variance(self, x_start, x_t, t):
209
+ """
210
+ Compute the mean and variance of the diffusion posterior:
211
+
212
+ q(x_{t-1} | x_t, x_0)
213
+
214
+ """
215
+ assert x_start.shape == x_t.shape
216
+ posterior_mean = (
217
+ _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start
218
+ + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
219
+ )
220
+ posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape)
221
+ posterior_log_variance_clipped = _extract_into_tensor(
222
+ self.posterior_log_variance_clipped, t, x_t.shape
223
+ )
224
+ assert (
225
+ posterior_mean.shape[0]
226
+ == posterior_variance.shape[0]
227
+ == posterior_log_variance_clipped.shape[0]
228
+ == x_start.shape[0]
229
+ )
230
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
231
+
232
+ def p_mean_variance(
233
+ self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None
234
+ ):
235
+ """
236
+ Apply the model to get p(x_{t-1} | x_t), as well as a prediction of
237
+ the initial x, x_0.
238
+
239
+ :param model: the model, which takes a signal and a batch of timesteps
240
+ as input.
241
+ :param x: the [N x C x ...] tensor at time t.
242
+ :param t: a 1-D Tensor of timesteps.
243
+ :param clip_denoised: if True, clip the denoised signal into [-1, 1].
244
+ :param denoised_fn: if not None, a function which applies to the
245
+ x_start prediction before it is used to sample. Applies before
246
+ clip_denoised.
247
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
248
+ pass to the model. This can be used for conditioning.
249
+ :return: a dict with the following keys:
250
+ - 'mean': the model mean output.
251
+ - 'variance': the model variance output.
252
+ - 'log_variance': the log of 'variance'.
253
+ - 'pred_xstart': the prediction for x_0.
254
+ """
255
+ if model_kwargs is None:
256
+ model_kwargs = {}
257
+
258
+ B, C = x.shape[:2]
259
+ assert t.shape == (B,)
260
+ model_output = model(x, self._scale_timesteps(t), **model_kwargs)
261
+
262
+ if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]:
263
+ assert model_output.shape == (B, C * 2, *x.shape[2:])
264
+ model_output, model_var_values = th.split(model_output, C, dim=1)
265
+ if self.model_var_type == ModelVarType.LEARNED:
266
+ model_log_variance = model_var_values
267
+ model_variance = th.exp(model_log_variance)
268
+ else:
269
+ min_log = _extract_into_tensor(
270
+ self.posterior_log_variance_clipped, t, x.shape
271
+ )
272
+ max_log = _extract_into_tensor(np.log(self.betas), t, x.shape)
273
+ # The model_var_values is [-1, 1] for [min_var, max_var].
274
+ frac = (model_var_values + 1) / 2
275
+ model_log_variance = frac * max_log + (1 - frac) * min_log
276
+ model_variance = th.exp(model_log_variance)
277
+ else:
278
+ model_variance, model_log_variance = {
279
+ # for fixedlarge, we set the initial (log-)variance like so
280
+ # to get a better decoder log likelihood.
281
+ ModelVarType.FIXED_LARGE: (
282
+ np.append(self.posterior_variance[1], self.betas[1:]),
283
+ np.log(np.append(self.posterior_variance[1], self.betas[1:])),
284
+ ),
285
+ ModelVarType.FIXED_SMALL: (
286
+ self.posterior_variance,
287
+ self.posterior_log_variance_clipped,
288
+ ),
289
+ }[self.model_var_type]
290
+ model_variance = _extract_into_tensor(model_variance, t, x.shape)
291
+ model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape)
292
+
293
+ def process_xstart(x):
294
+ if denoised_fn is not None:
295
+ x = denoised_fn(x)
296
+ if clip_denoised:
297
+ return x.clamp(-1, 1)
298
+ return x
299
+
300
+ if self.model_mean_type == ModelMeanType.PREVIOUS_X:
301
+ pred_xstart = process_xstart(
302
+ self._predict_xstart_from_xprev(x_t=x, t=t, xprev=model_output)
303
+ )
304
+ model_mean = model_output
305
+ elif self.model_mean_type in [ModelMeanType.START_X, ModelMeanType.EPSILON]:
306
+ if self.model_mean_type == ModelMeanType.START_X:
307
+ pred_xstart = process_xstart(model_output)
308
+ else:
309
+ pred_xstart = process_xstart(
310
+ self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)
311
+ )
312
+ model_mean, _, _ = self.q_posterior_mean_variance(
313
+ x_start=pred_xstart, x_t=x, t=t
314
+ )
315
+ else:
316
+ raise NotImplementedError(self.model_mean_type)
317
+
318
+ assert (
319
+ model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape
320
+ )
321
+ return {
322
+ "mean": model_mean,
323
+ "variance": model_variance,
324
+ "log_variance": model_log_variance,
325
+ "pred_xstart": pred_xstart,
326
+ }
327
+
328
+ def _predict_xstart_from_eps(self, x_t, t, eps):
329
+ assert x_t.shape == eps.shape
330
+ return (
331
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
332
+ - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps
333
+ )
334
+
335
+ def _predict_xstart_from_xprev(self, x_t, t, xprev):
336
+ assert x_t.shape == xprev.shape
337
+ return ( # (xprev - coef2*x_t) / coef1
338
+ _extract_into_tensor(1.0 / self.posterior_mean_coef1, t, x_t.shape) * xprev
339
+ - _extract_into_tensor(
340
+ self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape
341
+ )
342
+ * x_t
343
+ )
344
+
345
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
346
+ return (
347
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
348
+ - pred_xstart
349
+ ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
350
+
351
+ def _scale_timesteps(self, t):
352
+ if self.rescale_timesteps:
353
+ return t.float() * (1000.0 / self.num_timesteps)
354
+ return t
355
+
356
+ def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
357
+ """
358
+ Compute the mean for the previous step, given a function cond_fn that
359
+ computes the gradient of a conditional log probability with respect to
360
+ x. In particular, cond_fn computes grad(log(p(y|x))), and we want to
361
+ condition on y.
362
+
363
+ This uses the conditioning strategy from Sohl-Dickstein et al. (2015).
364
+ """
365
+ gradient = cond_fn(x, self._scale_timesteps(t), **model_kwargs)
366
+ new_mean = (
367
+ p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float()
368
+ )
369
+ return new_mean
370
+
371
+ def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
372
+ """
373
+ Compute what the p_mean_variance output would have been, should the
374
+ model's score function be conditioned by cond_fn.
375
+
376
+ See condition_mean() for details on cond_fn.
377
+
378
+ Unlike condition_mean(), this instead uses the conditioning strategy
379
+ from Song et al (2020).
380
+ """
381
+ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
382
+
383
+ eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"])
384
+ eps = eps - (1 - alpha_bar).sqrt() * cond_fn(
385
+ x, self._scale_timesteps(t), **model_kwargs
386
+ )
387
+
388
+ out = p_mean_var.copy()
389
+ out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps)
390
+ out["mean"], _, _ = self.q_posterior_mean_variance(
391
+ x_start=out["pred_xstart"], x_t=x, t=t
392
+ )
393
+ return out
394
+
395
+ def p_sample(
396
+ self,
397
+ model,
398
+ x,
399
+ t,
400
+ clip_denoised=True,
401
+ denoised_fn=None,
402
+ cond_fn=None,
403
+ model_kwargs=None,
404
+ ):
405
+ """
406
+ Sample x_{t-1} from the model at the given timestep.
407
+
408
+ :param model: the model to sample from.
409
+ :param x: the current tensor at x_{t-1}.
410
+ :param t: the value of t, starting at 0 for the first diffusion step.
411
+ :param clip_denoised: if True, clip the x_start prediction to [-1, 1].
412
+ :param denoised_fn: if not None, a function which applies to the
413
+ x_start prediction before it is used to sample.
414
+ :param cond_fn: if not None, this is a gradient function that acts
415
+ similarly to the model.
416
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
417
+ pass to the model. This can be used for conditioning.
418
+ :return: a dict containing the following keys:
419
+ - 'sample': a random sample from the model.
420
+ - 'pred_xstart': a prediction of x_0.
421
+ """
422
+ out = self.p_mean_variance(
423
+ model,
424
+ x,
425
+ t,
426
+ clip_denoised=clip_denoised,
427
+ denoised_fn=denoised_fn,
428
+ model_kwargs=model_kwargs,
429
+ )
430
+ noise = th.randn_like(x)
431
+ nonzero_mask = (
432
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
433
+ ) # no noise when t == 0
434
+ if cond_fn is not None:
435
+ out["mean"] = self.condition_mean(
436
+ cond_fn, out, x, t, model_kwargs=model_kwargs
437
+ )
438
+ sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise
439
+ return {"sample": sample, "pred_xstart": out["pred_xstart"]}
440
+
441
+ def p_sample_loop(
442
+ self,
443
+ model,
444
+ shape,
445
+ noise=None,
446
+ clip_denoised=True,
447
+ denoised_fn=None,
448
+ cond_fn=None,
449
+ model_kwargs=None,
450
+ device=None,
451
+ progress=False,
452
+ ):
453
+ """
454
+ Generate samples from the model.
455
+
456
+ :param model: the model module.
457
+ :param shape: the shape of the samples, (N, C, H, W).
458
+ :param noise: if specified, the noise from the encoder to sample.
459
+ Should be of the same shape as `shape`.
460
+ :param clip_denoised: if True, clip x_start predictions to [-1, 1].
461
+ :param denoised_fn: if not None, a function which applies to the
462
+ x_start prediction before it is used to sample.
463
+ :param cond_fn: if not None, this is a gradient function that acts
464
+ similarly to the model.
465
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
466
+ pass to the model. This can be used for conditioning.
467
+ :param device: if specified, the device to create the samples on.
468
+ If not specified, use a model parameter's device.
469
+ :param progress: if True, show a tqdm progress bar.
470
+ :return: a non-differentiable batch of samples.
471
+ """
472
+ final = None
473
+ for sample in self.p_sample_loop_progressive(
474
+ model,
475
+ shape,
476
+ noise=noise,
477
+ clip_denoised=clip_denoised,
478
+ denoised_fn=denoised_fn,
479
+ cond_fn=cond_fn,
480
+ model_kwargs=model_kwargs,
481
+ device=device,
482
+ progress=progress,
483
+ ):
484
+ final = sample
485
+ return final["sample"]
486
+
487
+ def p_sample_loop_progressive(
488
+ self,
489
+ model,
490
+ shape,
491
+ noise=None,
492
+ clip_denoised=True,
493
+ denoised_fn=None,
494
+ cond_fn=None,
495
+ model_kwargs=None,
496
+ device=None,
497
+ progress=False,
498
+ ):
499
+ """
500
+ Generate samples from the model and yield intermediate samples from
501
+ each timestep of diffusion.
502
+
503
+ Arguments are the same as p_sample_loop().
504
+ Returns a generator over dicts, where each dict is the return value of
505
+ p_sample().
506
+ """
507
+ if device is None:
508
+ device = next(model.parameters()).device
509
+ assert isinstance(shape, (tuple, list))
510
+ if noise is not None:
511
+ img = noise
512
+ else:
513
+ img = th.randn(*shape, device=device)
514
+ indices = list(range(self.num_timesteps))[::-1]
515
+
516
+ if progress:
517
+ # Lazy import so that we don't depend on tqdm.
518
+ from tqdm.auto import tqdm
519
+
520
+ indices = tqdm(indices)
521
+
522
+ for i in indices:
523
+ t = th.tensor([i] * shape[0], device=device)
524
+ with th.no_grad():
525
+ out = self.p_sample(
526
+ model,
527
+ img,
528
+ t,
529
+ clip_denoised=clip_denoised,
530
+ denoised_fn=denoised_fn,
531
+ cond_fn=cond_fn,
532
+ model_kwargs=model_kwargs,
533
+ )
534
+ yield out
535
+ img = out["sample"]
536
+
537
+ def ddim_sample(
538
+ self,
539
+ model,
540
+ x,
541
+ t,
542
+ clip_denoised=True,
543
+ denoised_fn=None,
544
+ cond_fn=None,
545
+ model_kwargs=None,
546
+ eta=0.0,
547
+ ):
548
+ """
549
+ Sample x_{t-1} from the model using DDIM.
550
+
551
+ Same usage as p_sample().
552
+ """
553
+ out = self.p_mean_variance(
554
+ model,
555
+ x,
556
+ t,
557
+ clip_denoised=clip_denoised,
558
+ denoised_fn=denoised_fn,
559
+ model_kwargs=model_kwargs,
560
+ )
561
+ if cond_fn is not None:
562
+ out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs)
563
+
564
+ # Usually our model outputs epsilon, but we re-derive it
565
+ # in case we used x_start or x_prev prediction.
566
+ eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
567
+
568
+ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
569
+ alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)
570
+ sigma = (
571
+ eta
572
+ * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
573
+ * th.sqrt(1 - alpha_bar / alpha_bar_prev)
574
+ )
575
+ # Equation 12.
576
+ noise = th.randn_like(x)
577
+ mean_pred = (
578
+ out["pred_xstart"] * th.sqrt(alpha_bar_prev)
579
+ + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps
580
+ )
581
+ nonzero_mask = (
582
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
583
+ ) # no noise when t == 0
584
+ sample = mean_pred + nonzero_mask * sigma * noise
585
+ return {"sample": sample, "pred_xstart": out["pred_xstart"]}
586
+
587
+ def ddim_reverse_sample(
588
+ self,
589
+ model,
590
+ x,
591
+ t,
592
+ clip_denoised=True,
593
+ denoised_fn=None,
594
+ model_kwargs=None,
595
+ eta=0.0,
596
+ ):
597
+ """
598
+ Sample x_{t+1} from the model using DDIM reverse ODE.
599
+ """
600
+ assert eta == 0.0, "Reverse ODE only for deterministic path"
601
+ out = self.p_mean_variance(
602
+ model,
603
+ x,
604
+ t,
605
+ clip_denoised=clip_denoised,
606
+ denoised_fn=denoised_fn,
607
+ model_kwargs=model_kwargs,
608
+ )
609
+ # Usually our model outputs epsilon, but we re-derive it
610
+ # in case we used x_start or x_prev prediction.
611
+ eps = (
612
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x
613
+ - out["pred_xstart"]
614
+ ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape)
615
+ alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape)
616
+
617
+ # Equation 12. reversed
618
+ mean_pred = (
619
+ out["pred_xstart"] * th.sqrt(alpha_bar_next)
620
+ + th.sqrt(1 - alpha_bar_next) * eps
621
+ )
622
+
623
+ return {"sample": mean_pred, "pred_xstart": out["pred_xstart"]}
624
+
625
+ def ddim_reverse_sample_only_eps(
626
+ self,
627
+ model,
628
+ x,
629
+ t,
630
+ clip_denoised=True,
631
+ denoised_fn=None,
632
+ model_kwargs=None,
633
+ eta=0.0,
634
+ ):
635
+ """
636
+ Sample x_{t+1} from the model using DDIM reverse ODE.
637
+ """
638
+ assert eta == 0.0, "Reverse ODE only for deterministic path"
639
+ out = self.p_mean_variance(
640
+ model,
641
+ x,
642
+ t,
643
+ clip_denoised=clip_denoised,
644
+ denoised_fn=denoised_fn,
645
+ model_kwargs=model_kwargs,
646
+ )
647
+ # Usually our model outputs epsilon, but we re-derive it
648
+ # in case we used x_start or x_prev prediction.
649
+ eps = (
650
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x
651
+ - out["pred_xstart"]
652
+ ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape)
653
+
654
+
655
+ return eps
656
+
657
+ def ddim_sample_loop(
658
+ self,
659
+ model,
660
+ shape,
661
+ noise=None,
662
+ clip_denoised=True,
663
+ denoised_fn=None,
664
+ cond_fn=None,
665
+ model_kwargs=None,
666
+ device=None,
667
+ progress=False,
668
+ eta=0.0,
669
+ return_intermediate=False,
670
+ real_step=0,
671
+ ):
672
+ """
673
+ Generate samples from the model using DDIM.
674
+
675
+ Same usage as p_sample_loop().
676
+ """
677
+ final = []
678
+ if return_intermediate:
679
+ step = int(self.num_timesteps//100) if self.num_timesteps>100 else 1
680
+ i = 0
681
+ for sample in self.ddim_sample_loop_progressive(
682
+ model,
683
+ shape,
684
+ noise=noise,
685
+ clip_denoised=clip_denoised,
686
+ denoised_fn=denoised_fn,
687
+ cond_fn=cond_fn,
688
+ model_kwargs=model_kwargs,
689
+ device=device,
690
+ progress=progress,
691
+ eta=eta,
692
+ real_step=real_step
693
+ ):
694
+ if return_intermediate:
695
+ i = i+1
696
+ if i % step==0:
697
+ final.append(sample["sample"])
698
+ else:
699
+ final = sample["sample"]
700
+ return final
701
+
702
+ def ddim_sample_loop_progressive(
703
+ self,
704
+ model,
705
+ shape,
706
+ noise=None,
707
+ clip_denoised=True,
708
+ denoised_fn=None,
709
+ cond_fn=None,
710
+ model_kwargs=None,
711
+ device=None,
712
+ progress=False,
713
+ eta=0.0,
714
+ real_step=0
715
+ ):
716
+ """
717
+ Use DDIM to sample from the model and yield intermediate samples from
718
+ each timestep of DDIM.
719
+
720
+ Same usage as p_sample_loop_progressive().
721
+ """
722
+ if device is None:
723
+ device = next(model.parameters()).device
724
+ assert isinstance(shape, (tuple, list))
725
+ if noise is not None:
726
+ img = noise
727
+ else:
728
+ img = th.randn(*shape, device=device)
729
+ indices = list(range(self.num_timesteps))[::-1] if not real_step else list(range(self.num_timesteps))[:real_step][::-1]
730
+ if progress:
731
+ # Lazy import so that we don't depend on tqdm.
732
+ from tqdm.auto import tqdm
733
+
734
+ indices = tqdm(indices)
735
+
736
+ for i in indices:
737
+ t = th.tensor([i] * shape[0], device=device)
738
+ with th.no_grad():
739
+ out = self.ddim_sample(
740
+ model,
741
+ img,
742
+ t,
743
+ clip_denoised=clip_denoised,
744
+ denoised_fn=denoised_fn,
745
+ cond_fn=cond_fn,
746
+ model_kwargs=model_kwargs,
747
+ eta=eta,
748
+ )
749
+ yield out
750
+ img = out["sample"]
751
+
752
+ def ddim_reverse_sample_loop(
753
+ self,
754
+ model,
755
+ shape,
756
+ noise=None,
757
+ clip_denoised=True,
758
+ denoised_fn=None,
759
+ cond_fn=None,
760
+ model_kwargs=None,
761
+ device=None,
762
+ progress=False,
763
+ eta=0.0,
764
+ real_step=0
765
+ ):
766
+ """
767
+ Generate samples from the model using DDIM.
768
+
769
+ Same usage as p_sample_loop().
770
+ """
771
+ final = None
772
+ for sample in self.ddim_reverse_sample_loop_progressive(
773
+ model,
774
+ shape,
775
+ noise=noise,
776
+ clip_denoised=clip_denoised,
777
+ denoised_fn=denoised_fn,
778
+ cond_fn=cond_fn,
779
+ model_kwargs=model_kwargs,
780
+ device=device,
781
+ progress=progress,
782
+ eta=eta,
783
+ real_step=real_step
784
+ ):
785
+ final = sample
786
+ return final["sample"]
787
+
788
+ def ddim_reverse_sample_loop_progressive(
789
+ self,
790
+ model,
791
+ shape,
792
+ noise=None,
793
+ clip_denoised=True,
794
+ denoised_fn=None,
795
+ cond_fn=None,
796
+ model_kwargs=None,
797
+ device=None,
798
+ progress=False,
799
+ eta=0.0,
800
+ real_step=0
801
+ ):
802
+ """
803
+ Use DDIM to sample from the model and yield intermediate samples from
804
+ each timestep of DDIM.
805
+
806
+ Same usage as p_sample_loop_progressive().
807
+ """
808
+ if device is None:
809
+ device = next(model.parameters()).device
810
+ assert isinstance(shape, (tuple, list))
811
+ if noise is not None:
812
+ img = noise
813
+ else:
814
+ img = th.randn(*shape, device=device)
815
+ # print(real_step, type(real_step))
816
+ indices = list(range(self.num_timesteps)) if real_step==0 else list(range(self.num_timesteps))[:real_step]#[::-1] # 1, ..., T
817
+
818
+ if progress:
819
+ # Lazy import so that we don't depend on tqdm.
820
+ from tqdm.auto import tqdm
821
+
822
+ indices = tqdm(indices)
823
+
824
+ for i in indices:
825
+ t = th.tensor([i] * shape[0], device=device)
826
+ with th.no_grad():
827
+ out = self.ddim_reverse_sample(
828
+ model,
829
+ img,
830
+ t,
831
+ clip_denoised=clip_denoised,
832
+ denoised_fn=denoised_fn,
833
+ model_kwargs=model_kwargs,
834
+ eta=eta,
835
+ )
836
+ yield out
837
+ img = out["sample"]
838
+
839
+ def _vb_terms_bpd(
840
+ self, model, x_start, x_t, t, clip_denoised=True, model_kwargs=None
841
+ ):
842
+ """
843
+ Get a term for the variational lower-bound.
844
+
845
+ The resulting units are bits (rather than nats, as one might expect).
846
+ This allows for comparison to other papers.
847
+
848
+ :return: a dict with the following keys:
849
+ - 'output': a shape [N] tensor of NLLs or KLs.
850
+ - 'pred_xstart': the x_0 predictions.
851
+ """
852
+ true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance(
853
+ x_start=x_start, x_t=x_t, t=t
854
+ )
855
+ out = self.p_mean_variance(
856
+ model, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs
857
+ )
858
+ kl = normal_kl(
859
+ true_mean, true_log_variance_clipped, out["mean"], out["log_variance"]
860
+ )
861
+ kl = mean_flat(kl) / np.log(2.0)
862
+
863
+ decoder_nll = -discretized_gaussian_log_likelihood(
864
+ x_start, means=out["mean"], log_scales=0.5 * out["log_variance"]
865
+ )
866
+ assert decoder_nll.shape == x_start.shape
867
+ decoder_nll = mean_flat(decoder_nll) / np.log(2.0)
868
+
869
+ # At the first timestep return the decoder NLL,
870
+ # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))
871
+ output = th.where((t == 0), decoder_nll, kl)
872
+ return {"output": output, "pred_xstart": out["pred_xstart"]}
873
+
874
+ def training_losses(self, model, x_start, t, model_kwargs=None, noise=None):
875
+ """
876
+ Compute training losses for a single timestep.
877
+
878
+ :param model: the model to evaluate loss on.
879
+ :param x_start: the [N x C x ...] tensor of inputs.
880
+ :param t: a batch of timestep indices.
881
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
882
+ pass to the model. This can be used for conditioning.
883
+ :param noise: if specified, the specific Gaussian noise to try to remove.
884
+ :return: a dict with the key "loss" containing a tensor of shape [N].
885
+ Some mean or variance settings may also have other keys.
886
+ """
887
+ if model_kwargs is None:
888
+ model_kwargs = {}
889
+ if noise is None:
890
+ noise = th.randn_like(x_start)
891
+ x_t = self.q_sample(x_start, t, noise=noise)
892
+
893
+ terms = {}
894
+
895
+ if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL:
896
+ terms["loss"] = self._vb_terms_bpd(
897
+ model=model,
898
+ x_start=x_start,
899
+ x_t=x_t,
900
+ t=t,
901
+ clip_denoised=False,
902
+ model_kwargs=model_kwargs,
903
+ )["output"]
904
+ if self.loss_type == LossType.RESCALED_KL:
905
+ terms["loss"] *= self.num_timesteps
906
+ elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE:
907
+ model_output = model(x_t, self._scale_timesteps(t), **model_kwargs)
908
+
909
+ if self.model_var_type in [
910
+ ModelVarType.LEARNED,
911
+ ModelVarType.LEARNED_RANGE,
912
+ ]:
913
+ B, C = x_t.shape[:2]
914
+ assert model_output.shape == (B, C * 2, *x_t.shape[2:])
915
+ model_output, model_var_values = th.split(model_output, C, dim=1)
916
+ # Learn the variance using the variational bound, but don't let
917
+ # it affect our mean prediction.
918
+ frozen_out = th.cat([model_output.detach(), model_var_values], dim=1)
919
+ terms["vb"] = self._vb_terms_bpd(
920
+ model=lambda *args, r=frozen_out: r,
921
+ x_start=x_start,
922
+ x_t=x_t,
923
+ t=t,
924
+ clip_denoised=False,
925
+ )["output"]
926
+ if self.loss_type == LossType.RESCALED_MSE:
927
+ # Divide by 1000 for equivalence with initial implementation.
928
+ # Without a factor of 1/1000, the VB term hurts the MSE term.
929
+ terms["vb"] *= self.num_timesteps / 1000.0
930
+
931
+ target = {
932
+ ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance(
933
+ x_start=x_start, x_t=x_t, t=t
934
+ )[0],
935
+ ModelMeanType.START_X: x_start,
936
+ ModelMeanType.EPSILON: noise,
937
+ }[self.model_mean_type]
938
+ assert model_output.shape == target.shape == x_start.shape
939
+ terms["mse"] = mean_flat((target - model_output) ** 2)
940
+ if "vb" in terms:
941
+ terms["loss"] = terms["mse"] + terms["vb"]
942
+ else:
943
+ terms["loss"] = terms["mse"]
944
+ else:
945
+ raise NotImplementedError(self.loss_type)
946
+
947
+ return terms
948
+
949
+ def _prior_bpd(self, x_start):
950
+ """
951
+ Get the prior KL term for the variational lower-bound, measured in
952
+ bits-per-dim.
953
+
954
+ This term can't be optimized, as it only depends on the encoder.
955
+
956
+ :param x_start: the [N x C x ...] tensor of inputs.
957
+ :return: a batch of [N] KL values (in bits), one per batch element.
958
+ """
959
+ batch_size = x_start.shape[0]
960
+ t = th.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
961
+ qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
962
+ kl_prior = normal_kl(
963
+ mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0
964
+ )
965
+ return mean_flat(kl_prior) / np.log(2.0)
966
+
967
+ def calc_bpd_loop(self, model, x_start, clip_denoised=True, model_kwargs=None):
968
+ """
969
+ Compute the entire variational lower-bound, measured in bits-per-dim,
970
+ as well as other related quantities.
971
+
972
+ :param model: the model to evaluate loss on.
973
+ :param x_start: the [N x C x ...] tensor of inputs.
974
+ :param clip_denoised: if True, clip denoised samples.
975
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
976
+ pass to the model. This can be used for conditioning.
977
+
978
+ :return: a dict containing the following keys:
979
+ - total_bpd: the total variational lower-bound, per batch element.
980
+ - prior_bpd: the prior term in the lower-bound.
981
+ - vb: an [N x T] tensor of terms in the lower-bound.
982
+ - xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep.
983
+ - mse: an [N x T] tensor of epsilon MSEs for each timestep.
984
+ """
985
+ device = x_start.device
986
+ batch_size = x_start.shape[0]
987
+
988
+ vb = []
989
+ xstart_mse = []
990
+ mse = []
991
+ for t in list(range(self.num_timesteps))[::-1]:
992
+ t_batch = th.tensor([t] * batch_size, device=device)
993
+ noise = th.randn_like(x_start)
994
+ x_t = self.q_sample(x_start=x_start, t=t_batch, noise=noise)
995
+ # Calculate VLB term at the current timestep
996
+ with th.no_grad():
997
+ out = self._vb_terms_bpd(
998
+ model,
999
+ x_start=x_start,
1000
+ x_t=x_t,
1001
+ t=t_batch,
1002
+ clip_denoised=clip_denoised,
1003
+ model_kwargs=model_kwargs,
1004
+ )
1005
+ vb.append(out["output"])
1006
+ xstart_mse.append(mean_flat((out["pred_xstart"] - x_start) ** 2))
1007
+ eps = self._predict_eps_from_xstart(x_t, t_batch, out["pred_xstart"])
1008
+ mse.append(mean_flat((eps - noise) ** 2))
1009
+
1010
+ vb = th.stack(vb, dim=1)
1011
+ xstart_mse = th.stack(xstart_mse, dim=1)
1012
+ mse = th.stack(mse, dim=1)
1013
+
1014
+ prior_bpd = self._prior_bpd(x_start)
1015
+ total_bpd = vb.sum(dim=1) + prior_bpd
1016
+ return {
1017
+ "total_bpd": total_bpd,
1018
+ "prior_bpd": prior_bpd,
1019
+ "vb": vb,
1020
+ "xstart_mse": xstart_mse,
1021
+ "mse": mse,
1022
+ }
1023
+
1024
+
1025
+ def _extract_into_tensor(arr, timesteps, broadcast_shape):
1026
+ """
1027
+ Extract values from a 1-D numpy array for a batch of indices.
1028
+
1029
+ :param arr: the 1-D numpy array.
1030
+ :param timesteps: a tensor of indices into the array to extract.
1031
+ :param broadcast_shape: a larger shape of K dimensions with the batch
1032
+ dimension equal to the length of timesteps.
1033
+ :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims.
1034
+ """
1035
+ res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float()
1036
+ while len(res.shape) < len(broadcast_shape):
1037
+ res = res[..., None]
1038
+ return res.expand(broadcast_shape)
guided_diffusion/guided_diffusion/image_datasets.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+
5
+ from PIL import Image
6
+ import blobfile as bf
7
+ from mpi4py import MPI
8
+ import numpy as np
9
+ import torch
10
+ from torch.utils.data import DataLoader, Dataset
11
+ from guided_diffusion import logger
12
+
13
+
14
+ def load_data_for_reverse(
15
+ *,
16
+ data_dir,
17
+ batch_size,
18
+ image_size,
19
+ class_cond=False,
20
+ deterministic=True,
21
+ random_crop=False,
22
+ random_flip=False,
23
+ ):
24
+ """
25
+ For a dataset, create a generator over (images, kwargs) pairs.
26
+
27
+ Each images is an NCHW float tensor, and the kwargs dict contains zero or
28
+ more keys, each of which map to a batched Tensor of their own.
29
+ The kwargs dict can be used for class labels, in which case the key is "y"
30
+ and the values are integer tensors of class labels. # kwargs包含了标签信息
31
+
32
+ :param data_dir: a dataset directory.
33
+ :param batch_size: the batch size of each returned pair.
34
+ :param image_size: the size to which images are resized.
35
+ :param class_cond: if True, include a "y" key in returned dicts for class
36
+ label. If classes are not available and this is true, an
37
+ exception will be raised.
38
+ :param deterministic: if True, yield results in a deterministic order.
39
+ :param random_crop: if True, randomly crop the images for augmentation.
40
+ :param random_flip: if True, randomly flip the images for augmentation.
41
+ """
42
+ if not data_dir:
43
+ raise ValueError("unspecified data directory")
44
+ if MPI.COMM_WORLD.Get_rank() == 0:
45
+ all_files = _list_image_files_recursively(data_dir)
46
+
47
+ if MPI.COMM_WORLD.Get_rank() == 0:
48
+ MPI.COMM_WORLD.bcast(all_files)
49
+ else:
50
+ all_files = MPI.COMM_WORLD.bcast(None)
51
+
52
+ classes = None
53
+ if class_cond:
54
+ # Assume classes are the first part of the filename,
55
+ # before an underscore.
56
+ class_names = [bf.basename(path).split("_")[0] for path in all_files] # 标签_文件名
57
+ sorted_classes = {x: i for i, x in enumerate(sorted(set(class_names)))}
58
+ classes = [sorted_classes[x] for x in class_names]
59
+ dataset = ImageDataset_for_reverse(
60
+ image_size,
61
+ all_files,
62
+ classes=classes,
63
+ shard=MPI.COMM_WORLD.Get_rank(),
64
+ num_shards=MPI.COMM_WORLD.Get_size(),
65
+ random_crop=random_crop,
66
+ random_flip=random_flip,
67
+ )
68
+ logger.log("dataset length: {}".format(dataset.__len__() * MPI.COMM_WORLD.size))
69
+ if deterministic:
70
+ loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=1, drop_last=False)
71
+ else:
72
+ loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=1, drop_last=True)
73
+ while True:
74
+ yield from loader
75
+
76
+
77
+ def load_data(
78
+ *,
79
+ data_dir,
80
+ batch_size,
81
+ image_size,
82
+ class_cond=False,
83
+ deterministic=False,
84
+ random_crop=False,
85
+ random_flip=True,
86
+ ):
87
+ """
88
+ For a dataset, create a generator over (images, kwargs) pairs.
89
+
90
+ Each images is an NCHW float tensor, and the kwargs dict contains zero or
91
+ more keys, each of which map to a batched Tensor of their own.
92
+ The kwargs dict can be used for class labels, in which case the key is "y"
93
+ and the values are integer tensors of class labels.
94
+
95
+ :param data_dir: a dataset directory.
96
+ :param batch_size: the batch size of each returned pair.
97
+ :param image_size: the size to which images are resized.
98
+ :param class_cond: if True, include a "y" key in returned dicts for class
99
+ label. If classes are not available and this is true, an
100
+ exception will be raised.
101
+ :param deterministic: if True, yield results in a deterministic order.
102
+ :param random_crop: if True, randomly crop the images for augmentation.
103
+ :param random_flip: if True, randomly flip the images for augmentation.
104
+ """
105
+ if not data_dir:
106
+ raise ValueError("unspecified data directory")
107
+ all_files = _list_image_files_recursively(data_dir)
108
+ classes = None
109
+ if class_cond:
110
+ # Assume classes are the first part of the filename,
111
+ # before an underscore.
112
+ class_names = [bf.basename(path).split("_")[0] for path in all_files]
113
+ sorted_classes = {x: i for i, x in enumerate(sorted(set(class_names)))}
114
+ classes = [sorted_classes[x] for x in class_names]
115
+ dataset = ImageDataset(
116
+ image_size,
117
+ all_files,
118
+ classes=classes,
119
+ shard=MPI.COMM_WORLD.Get_rank(),
120
+ num_shards=MPI.COMM_WORLD.Get_size(),
121
+ random_crop=random_crop,
122
+ random_flip=random_flip,
123
+ )
124
+ if deterministic:
125
+ loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=1, drop_last=True)
126
+ else:
127
+ loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=1, drop_last=True)
128
+ while True:
129
+ yield from loader
130
+
131
+
132
+ def _list_image_files_recursively(data_dir):
133
+ results = []
134
+ for entry in sorted(bf.listdir(data_dir)):
135
+ full_path = bf.join(data_dir, entry)
136
+ ext = entry.split(".")[-1]
137
+ if "." in entry and ext.lower() in ["jpg", "jpeg", "png", "gif"]:
138
+ results.append(full_path)
139
+ elif bf.isdir(full_path):
140
+ results.extend(_list_image_files_recursively(full_path))
141
+ return results
142
+
143
+
144
+ class ImageDataset_for_reverse(Dataset):
145
+ def __init__(
146
+ self,
147
+ resolution,
148
+ image_paths,
149
+ classes=None,
150
+ shard=0,
151
+ num_shards=1,
152
+ random_crop=False,
153
+ random_flip=True,
154
+ ):
155
+ super().__init__()
156
+ self.resolution = resolution
157
+ self.local_images = image_paths[shard:][::num_shards]
158
+ self.local_classes = None if classes is None else classes[shard:][::num_shards]
159
+ self.random_crop = random_crop
160
+ self.random_flip = random_flip
161
+
162
+ def __len__(self):
163
+ return len(self.local_images)
164
+
165
+ def __getitem__(self, idx):
166
+ path = self.local_images[idx]
167
+ with bf.BlobFile(path, "rb") as f:
168
+ pil_image = Image.open(f)
169
+ pil_image.load()
170
+ pil_image = pil_image.convert("RGB")
171
+
172
+ if self.random_crop:
173
+ arr = random_crop_arr(pil_image, self.resolution)
174
+ else:
175
+ arr = center_crop_arr(pil_image, self.resolution)
176
+
177
+ if self.random_flip and random.random() < 0.5:
178
+ arr = arr[:, ::-1]
179
+
180
+ arr = arr.astype(np.float32) / 127.5 - 1
181
+
182
+ out_dict = {}
183
+ if self.local_classes is not None:
184
+ out_dict["y"] = np.array(self.local_classes[idx], dtype=np.int64)
185
+ arr = torch.from_numpy(np.transpose(arr, [2, 0, 1]))
186
+ return arr, out_dict, path
187
+
188
+
189
+ class ImageDataset(Dataset):
190
+ def __init__(
191
+ self,
192
+ resolution,
193
+ image_paths,
194
+ classes=None,
195
+ shard=0,
196
+ num_shards=1,
197
+ random_crop=False,
198
+ random_flip=True,
199
+ ):
200
+ super().__init__()
201
+ self.resolution = resolution
202
+ self.local_images = image_paths[shard:][::num_shards]
203
+ self.local_classes = None if classes is None else classes[shard:][::num_shards]
204
+ self.random_crop = random_crop
205
+ self.random_flip = random_flip
206
+
207
+ def __len__(self):
208
+ return len(self.local_images)
209
+
210
+ def __getitem__(self, idx):
211
+ path = self.local_images[idx]
212
+ with bf.BlobFile(path, "rb") as f:
213
+ pil_image = Image.open(f)
214
+ pil_image.load()
215
+ pil_image = pil_image.convert("RGB")
216
+
217
+ if self.random_crop:
218
+ arr = random_crop_arr(pil_image, self.resolution)
219
+ else:
220
+ arr = center_crop_arr(pil_image, self.resolution)
221
+
222
+ if self.random_flip and random.random() < 0.5:
223
+ arr = arr[:, ::-1]
224
+
225
+ arr = arr.astype(np.float32) / 127.5 - 1
226
+
227
+ out_dict = {}
228
+ if self.local_classes is not None:
229
+ out_dict["y"] = np.array(self.local_classes[idx], dtype=np.int64)
230
+ return np.transpose(arr, [2, 0, 1]), out_dict
231
+
232
+
233
+ def center_crop_arr(pil_image, image_size):
234
+ # We are not on a new enough PIL to support the `reducing_gap`
235
+ # argument, which uses BOX downsampling at powers of two first.
236
+ # Thus, we do it by hand to improve downsample quality.
237
+ while min(*pil_image.size) >= 2 * image_size:
238
+ pil_image = pil_image.resize(tuple(x // 2 for x in pil_image.size), resample=Image.BOX)
239
+
240
+ scale = image_size / min(*pil_image.size)
241
+ pil_image = pil_image.resize(tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC)
242
+
243
+ arr = np.array(pil_image)
244
+ crop_y = (arr.shape[0] - image_size) // 2
245
+ crop_x = (arr.shape[1] - image_size) // 2
246
+ return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size]
247
+
248
+
249
+ def random_crop_arr(pil_image, image_size, min_crop_frac=0.8, max_crop_frac=1.0):
250
+ min_smaller_dim_size = math.ceil(image_size / max_crop_frac)
251
+ max_smaller_dim_size = math.ceil(image_size / min_crop_frac)
252
+ smaller_dim_size = random.randrange(min_smaller_dim_size, max_smaller_dim_size + 1)
253
+
254
+ # We are not on a new enough PIL to support the `reducing_gap`
255
+ # argument, which uses BOX downsampling at powers of two first.
256
+ # Thus, we do it by hand to improve downsample quality.
257
+ while min(*pil_image.size) >= 2 * smaller_dim_size:
258
+ pil_image = pil_image.resize(tuple(x // 2 for x in pil_image.size), resample=Image.BOX)
259
+
260
+ scale = smaller_dim_size / min(*pil_image.size)
261
+ pil_image = pil_image.resize(tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC)
262
+
263
+ arr = np.array(pil_image)
264
+ crop_y = random.randrange(arr.shape[0] - image_size + 1)
265
+ crop_x = random.randrange(arr.shape[1] - image_size + 1)
266
+ return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size]
guided_diffusion/guided_diffusion/logger.py ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Logger copied from OpenAI baselines to avoid extra RL-based dependencies:
3
+ https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/logger.py
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ import shutil
9
+ import os.path as osp
10
+ import json
11
+ import time
12
+ import datetime
13
+ import tempfile
14
+ import warnings
15
+ from collections import defaultdict
16
+ from contextlib import contextmanager
17
+
18
+ DEBUG = 10
19
+ INFO = 20
20
+ WARN = 30
21
+ ERROR = 40
22
+
23
+ DISABLED = 50
24
+
25
+
26
+ class KVWriter(object):
27
+ def writekvs(self, kvs):
28
+ raise NotImplementedError
29
+
30
+
31
+ class SeqWriter(object):
32
+ def writeseq(self, seq):
33
+ raise NotImplementedError
34
+
35
+
36
+ class HumanOutputFormat(KVWriter, SeqWriter):
37
+ def __init__(self, filename_or_file):
38
+ if isinstance(filename_or_file, str):
39
+ self.file = open(filename_or_file, "wt")
40
+ self.own_file = True
41
+ else:
42
+ assert hasattr(filename_or_file, "read"), (
43
+ "expected file or str, got %s" % filename_or_file
44
+ )
45
+ self.file = filename_or_file
46
+ self.own_file = False
47
+
48
+ def writekvs(self, kvs):
49
+ # Create strings for printing
50
+ key2str = {}
51
+ for (key, val) in sorted(kvs.items()):
52
+ if hasattr(val, "__float__"):
53
+ valstr = "%-8.3g" % val
54
+ else:
55
+ valstr = str(val)
56
+ key2str[self._truncate(key)] = self._truncate(valstr)
57
+
58
+ # Find max widths
59
+ if len(key2str) == 0:
60
+ print("WARNING: tried to write empty key-value dict")
61
+ return
62
+ else:
63
+ keywidth = max(map(len, key2str.keys()))
64
+ valwidth = max(map(len, key2str.values()))
65
+
66
+ # Write out the data
67
+ dashes = "-" * (keywidth + valwidth + 7)
68
+ lines = [dashes]
69
+ for (key, val) in sorted(key2str.items(), key=lambda kv: kv[0].lower()):
70
+ lines.append(
71
+ "| %s%s | %s%s |"
72
+ % (key, " " * (keywidth - len(key)), val, " " * (valwidth - len(val)))
73
+ )
74
+ lines.append(dashes)
75
+ self.file.write("\n".join(lines) + "\n")
76
+
77
+ # Flush the output to the file
78
+ self.file.flush()
79
+
80
+ def _truncate(self, s):
81
+ maxlen = 30
82
+ return s[: maxlen - 3] + "..." if len(s) > maxlen else s
83
+
84
+ def writeseq(self, seq):
85
+ seq = list(seq)
86
+ for (i, elem) in enumerate(seq):
87
+ self.file.write(elem)
88
+ if i < len(seq) - 1: # add space unless this is the last one
89
+ self.file.write(" ")
90
+ self.file.write("\n")
91
+ self.file.flush()
92
+
93
+ def close(self):
94
+ if self.own_file:
95
+ self.file.close()
96
+
97
+
98
+ class JSONOutputFormat(KVWriter):
99
+ def __init__(self, filename):
100
+ self.file = open(filename, "wt")
101
+
102
+ def writekvs(self, kvs):
103
+ for k, v in sorted(kvs.items()):
104
+ if hasattr(v, "dtype"):
105
+ kvs[k] = float(v)
106
+ self.file.write(json.dumps(kvs) + "\n")
107
+ self.file.flush()
108
+
109
+ def close(self):
110
+ self.file.close()
111
+
112
+
113
+ class CSVOutputFormat(KVWriter):
114
+ def __init__(self, filename):
115
+ self.file = open(filename, "w+t")
116
+ self.keys = []
117
+ self.sep = ","
118
+
119
+ def writekvs(self, kvs):
120
+ # Add our current row to the history
121
+ extra_keys = list(kvs.keys() - self.keys)
122
+ extra_keys.sort()
123
+ if extra_keys:
124
+ self.keys.extend(extra_keys)
125
+ self.file.seek(0)
126
+ lines = self.file.readlines()
127
+ self.file.seek(0)
128
+ for (i, k) in enumerate(self.keys):
129
+ if i > 0:
130
+ self.file.write(",")
131
+ self.file.write(k)
132
+ self.file.write("\n")
133
+ for line in lines[1:]:
134
+ self.file.write(line[:-1])
135
+ self.file.write(self.sep * len(extra_keys))
136
+ self.file.write("\n")
137
+ for (i, k) in enumerate(self.keys):
138
+ if i > 0:
139
+ self.file.write(",")
140
+ v = kvs.get(k)
141
+ if v is not None:
142
+ self.file.write(str(v))
143
+ self.file.write("\n")
144
+ self.file.flush()
145
+
146
+ def close(self):
147
+ self.file.close()
148
+
149
+
150
+ class TensorBoardOutputFormat(KVWriter):
151
+ """
152
+ Dumps key/value pairs into TensorBoard's numeric format.
153
+ """
154
+
155
+ def __init__(self, dir):
156
+ os.makedirs(dir, exist_ok=True)
157
+ self.dir = dir
158
+ self.step = 1
159
+ prefix = "events"
160
+ path = osp.join(osp.abspath(dir), prefix)
161
+ import tensorflow as tf
162
+ from tensorflow.python import pywrap_tensorflow
163
+ from tensorflow.core.util import event_pb2
164
+ from tensorflow.python.util import compat
165
+
166
+ self.tf = tf
167
+ self.event_pb2 = event_pb2
168
+ self.pywrap_tensorflow = pywrap_tensorflow
169
+ self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path))
170
+
171
+ def writekvs(self, kvs):
172
+ def summary_val(k, v):
173
+ kwargs = {"tag": k, "simple_value": float(v)}
174
+ return self.tf.Summary.Value(**kwargs)
175
+
176
+ summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()])
177
+ event = self.event_pb2.Event(wall_time=time.time(), summary=summary)
178
+ event.step = (
179
+ self.step
180
+ ) # is there any reason why you'd want to specify the step?
181
+ self.writer.WriteEvent(event)
182
+ self.writer.Flush()
183
+ self.step += 1
184
+
185
+ def close(self):
186
+ if self.writer:
187
+ self.writer.Close()
188
+ self.writer = None
189
+
190
+
191
+ def make_output_format(format, ev_dir, log_suffix=""):
192
+ os.makedirs(ev_dir, exist_ok=True)
193
+ if format == "stdout":
194
+ return HumanOutputFormat(sys.stdout)
195
+ elif format == "log":
196
+ return HumanOutputFormat(osp.join(ev_dir, "log%s.txt" % log_suffix))
197
+ elif format == "json":
198
+ return JSONOutputFormat(osp.join(ev_dir, "progress%s.json" % log_suffix))
199
+ elif format == "csv":
200
+ return CSVOutputFormat(osp.join(ev_dir, "progress%s.csv" % log_suffix))
201
+ elif format == "tensorboard":
202
+ return TensorBoardOutputFormat(osp.join(ev_dir, "tb%s" % log_suffix))
203
+ else:
204
+ raise ValueError("Unknown format specified: %s" % (format,))
205
+
206
+
207
+ # ================================================================
208
+ # API
209
+ # ================================================================
210
+
211
+
212
+ def logkv(key, val):
213
+ """
214
+ Log a value of some diagnostic
215
+ Call this once for each diagnostic quantity, each iteration
216
+ If called many times, last value will be used.
217
+ """
218
+ get_current().logkv(key, val)
219
+
220
+
221
+ def logkv_mean(key, val):
222
+ """
223
+ The same as logkv(), but if called many times, values averaged.
224
+ """
225
+ get_current().logkv_mean(key, val)
226
+
227
+
228
+ def logkvs(d):
229
+ """
230
+ Log a dictionary of key-value pairs
231
+ """
232
+ for (k, v) in d.items():
233
+ logkv(k, v)
234
+
235
+
236
+ def dumpkvs():
237
+ """
238
+ Write all of the diagnostics from the current iteration
239
+ """
240
+ return get_current().dumpkvs()
241
+
242
+
243
+ def getkvs():
244
+ return get_current().name2val
245
+
246
+
247
+ def log(*args, level=INFO):
248
+ """
249
+ Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).
250
+ """
251
+ get_current().log(*args, level=level)
252
+
253
+
254
+ def debug(*args):
255
+ log(*args, level=DEBUG)
256
+
257
+
258
+ def info(*args):
259
+ log(*args, level=INFO)
260
+
261
+
262
+ def warn(*args):
263
+ log(*args, level=WARN)
264
+
265
+
266
+ def error(*args):
267
+ log(*args, level=ERROR)
268
+
269
+
270
+ def set_level(level):
271
+ """
272
+ Set logging threshold on current logger.
273
+ """
274
+ get_current().set_level(level)
275
+
276
+
277
+ def set_comm(comm):
278
+ get_current().set_comm(comm)
279
+
280
+
281
+ def get_dir():
282
+ """
283
+ Get directory that log files are being written to.
284
+ will be None if there is no output directory (i.e., if you didn't call start)
285
+ """
286
+ return get_current().get_dir()
287
+
288
+
289
+ record_tabular = logkv
290
+ dump_tabular = dumpkvs
291
+
292
+
293
+ @contextmanager
294
+ def profile_kv(scopename):
295
+ logkey = "wait_" + scopename
296
+ tstart = time.time()
297
+ try:
298
+ yield
299
+ finally:
300
+ get_current().name2val[logkey] += time.time() - tstart
301
+
302
+
303
+ def profile(n):
304
+ """
305
+ Usage:
306
+ @profile("my_func")
307
+ def my_func(): code
308
+ """
309
+
310
+ def decorator_with_name(func):
311
+ def func_wrapper(*args, **kwargs):
312
+ with profile_kv(n):
313
+ return func(*args, **kwargs)
314
+
315
+ return func_wrapper
316
+
317
+ return decorator_with_name
318
+
319
+
320
+ # ================================================================
321
+ # Backend
322
+ # ================================================================
323
+
324
+
325
+ def get_current():
326
+ if Logger.CURRENT is None:
327
+ _configure_default_logger()
328
+
329
+ return Logger.CURRENT
330
+
331
+
332
+ class Logger(object):
333
+ DEFAULT = None # A logger with no output files. (See right below class definition)
334
+ # So that you can still log to the terminal without setting up any output files
335
+ CURRENT = None # Current logger being used by the free functions above
336
+
337
+ def __init__(self, dir, output_formats, comm=None):
338
+ self.name2val = defaultdict(float) # values this iteration
339
+ self.name2cnt = defaultdict(int)
340
+ self.level = INFO
341
+ self.dir = dir
342
+ self.output_formats = output_formats
343
+ self.comm = comm
344
+
345
+ # Logging API, forwarded
346
+ # ----------------------------------------
347
+ def logkv(self, key, val):
348
+ self.name2val[key] = val
349
+
350
+ def logkv_mean(self, key, val):
351
+ oldval, cnt = self.name2val[key], self.name2cnt[key]
352
+ self.name2val[key] = oldval * cnt / (cnt + 1) + val / (cnt + 1)
353
+ self.name2cnt[key] = cnt + 1
354
+
355
+ def dumpkvs(self):
356
+ if self.comm is None:
357
+ d = self.name2val
358
+ else:
359
+ d = mpi_weighted_mean(
360
+ self.comm,
361
+ {
362
+ name: (val, self.name2cnt.get(name, 1))
363
+ for (name, val) in self.name2val.items()
364
+ },
365
+ )
366
+ if self.comm.rank != 0:
367
+ d["dummy"] = 1 # so we don't get a warning about empty dict
368
+ out = d.copy() # Return the dict for unit testing purposes
369
+ for fmt in self.output_formats:
370
+ if isinstance(fmt, KVWriter):
371
+ fmt.writekvs(d)
372
+ self.name2val.clear()
373
+ self.name2cnt.clear()
374
+ return out
375
+
376
+ def log(self, *args, level=INFO):
377
+ if self.level <= level:
378
+ self._do_log(args)
379
+
380
+ # Configuration
381
+ # ----------------------------------------
382
+ def set_level(self, level):
383
+ self.level = level
384
+
385
+ def set_comm(self, comm):
386
+ self.comm = comm
387
+
388
+ def get_dir(self):
389
+ return self.dir
390
+
391
+ def close(self):
392
+ for fmt in self.output_formats:
393
+ fmt.close()
394
+
395
+ # Misc
396
+ # ----------------------------------------
397
+ def _do_log(self, args):
398
+ for fmt in self.output_formats:
399
+ if isinstance(fmt, SeqWriter):
400
+ fmt.writeseq(map(str, args))
401
+
402
+
403
+ def get_rank_without_mpi_import():
404
+ # check environment variables here instead of importing mpi4py
405
+ # to avoid calling MPI_Init() when this module is imported
406
+ for varname in ["PMI_RANK", "OMPI_COMM_WORLD_RANK"]:
407
+ if varname in os.environ:
408
+ return int(os.environ[varname])
409
+ return 0
410
+
411
+
412
+ def mpi_weighted_mean(comm, local_name2valcount):
413
+ """
414
+ Copied from: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/common/mpi_util.py#L110
415
+ Perform a weighted average over dicts that are each on a different node
416
+ Input: local_name2valcount: dict mapping key -> (value, count)
417
+ Returns: key -> mean
418
+ """
419
+ all_name2valcount = comm.gather(local_name2valcount)
420
+ if comm.rank == 0:
421
+ name2sum = defaultdict(float)
422
+ name2count = defaultdict(float)
423
+ for n2vc in all_name2valcount:
424
+ for (name, (val, count)) in n2vc.items():
425
+ try:
426
+ val = float(val)
427
+ except ValueError:
428
+ if comm.rank == 0:
429
+ warnings.warn(
430
+ "WARNING: tried to compute mean on non-float {}={}".format(
431
+ name, val
432
+ )
433
+ )
434
+ else:
435
+ name2sum[name] += val * count
436
+ name2count[name] += count
437
+ return {name: name2sum[name] / name2count[name] for name in name2sum}
438
+ else:
439
+ return {}
440
+
441
+
442
+ def configure(dir=None, format_strs=None, comm=None, log_suffix=""):
443
+ """
444
+ If comm is provided, average all numerical stats across that comm
445
+ """
446
+ if dir is None:
447
+ dir = os.getenv("OPENAI_LOGDIR")
448
+ if dir is None:
449
+ dir = osp.join(
450
+ tempfile.gettempdir(),
451
+ datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"),
452
+ )
453
+ assert isinstance(dir, str)
454
+ dir = os.path.expanduser(dir)
455
+ os.makedirs(os.path.expanduser(dir), exist_ok=True)
456
+
457
+ rank = get_rank_without_mpi_import()
458
+ if rank > 0:
459
+ log_suffix = log_suffix + "-rank%03i" % rank
460
+
461
+ if format_strs is None:
462
+ if rank == 0:
463
+ format_strs = os.getenv("OPENAI_LOG_FORMAT", "stdout,log,csv").split(",")
464
+ else:
465
+ format_strs = os.getenv("OPENAI_LOG_FORMAT_MPI", "log").split(",")
466
+ format_strs = filter(None, format_strs)
467
+ output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs]
468
+
469
+ Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm)
470
+ if output_formats:
471
+ log("Logging to %s" % dir)
472
+
473
+
474
+ def _configure_default_logger():
475
+ configure()
476
+ Logger.DEFAULT = Logger.CURRENT
477
+
478
+
479
+ def reset():
480
+ if Logger.CURRENT is not Logger.DEFAULT:
481
+ Logger.CURRENT.close()
482
+ Logger.CURRENT = Logger.DEFAULT
483
+ log("Reset logger")
484
+
485
+
486
+ @contextmanager
487
+ def scoped_configure(dir=None, format_strs=None, comm=None):
488
+ prevlogger = Logger.CURRENT
489
+ configure(dir=dir, format_strs=format_strs, comm=comm)
490
+ try:
491
+ yield
492
+ finally:
493
+ Logger.CURRENT.close()
494
+ Logger.CURRENT = prevlogger
495
+
guided_diffusion/guided_diffusion/losses.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helpers for various likelihood-based losses. These are ported from the original
3
+ Ho et al. diffusion models codebase:
4
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/utils.py
5
+ """
6
+
7
+ import numpy as np
8
+
9
+ import torch as th
10
+
11
+
12
+ def normal_kl(mean1, logvar1, mean2, logvar2):
13
+ """
14
+ Compute the KL divergence between two gaussians.
15
+
16
+ Shapes are automatically broadcasted, so batches can be compared to
17
+ scalars, among other use cases.
18
+ """
19
+ tensor = None
20
+ for obj in (mean1, logvar1, mean2, logvar2):
21
+ if isinstance(obj, th.Tensor):
22
+ tensor = obj
23
+ break
24
+ assert tensor is not None, "at least one argument must be a Tensor"
25
+
26
+ # Force variances to be Tensors. Broadcasting helps convert scalars to
27
+ # Tensors, but it does not work for th.exp().
28
+ logvar1, logvar2 = [
29
+ x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor)
30
+ for x in (logvar1, logvar2)
31
+ ]
32
+
33
+ return 0.5 * (
34
+ -1.0
35
+ + logvar2
36
+ - logvar1
37
+ + th.exp(logvar1 - logvar2)
38
+ + ((mean1 - mean2) ** 2) * th.exp(-logvar2)
39
+ )
40
+
41
+
42
+ def approx_standard_normal_cdf(x):
43
+ """
44
+ A fast approximation of the cumulative distribution function of the
45
+ standard normal.
46
+ """
47
+ return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3))))
48
+
49
+
50
+ def discretized_gaussian_log_likelihood(x, *, means, log_scales):
51
+ """
52
+ Compute the log-likelihood of a Gaussian distribution discretizing to a
53
+ given image.
54
+
55
+ :param x: the target images. It is assumed that this was uint8 values,
56
+ rescaled to the range [-1, 1].
57
+ :param means: the Gaussian mean Tensor.
58
+ :param log_scales: the Gaussian log stddev Tensor.
59
+ :return: a tensor like x of log probabilities (in nats).
60
+ """
61
+ assert x.shape == means.shape == log_scales.shape
62
+ centered_x = x - means
63
+ inv_stdv = th.exp(-log_scales)
64
+ plus_in = inv_stdv * (centered_x + 1.0 / 255.0)
65
+ cdf_plus = approx_standard_normal_cdf(plus_in)
66
+ min_in = inv_stdv * (centered_x - 1.0 / 255.0)
67
+ cdf_min = approx_standard_normal_cdf(min_in)
68
+ log_cdf_plus = th.log(cdf_plus.clamp(min=1e-12))
69
+ log_one_minus_cdf_min = th.log((1.0 - cdf_min).clamp(min=1e-12))
70
+ cdf_delta = cdf_plus - cdf_min
71
+ log_probs = th.where(
72
+ x < -0.999,
73
+ log_cdf_plus,
74
+ th.where(x > 0.999, log_one_minus_cdf_min, th.log(cdf_delta.clamp(min=1e-12))),
75
+ )
76
+ assert log_probs.shape == x.shape
77
+ return log_probs
guided_diffusion/guided_diffusion/nn.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Various utilities for neural networks.
3
+ """
4
+
5
+ import math
6
+
7
+ import torch as th
8
+ import torch.nn as nn
9
+
10
+
11
+ # PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
12
+ class SiLU(nn.Module):
13
+ def forward(self, x):
14
+ return x * th.sigmoid(x)
15
+
16
+
17
+ class GroupNorm32(nn.GroupNorm):
18
+ def forward(self, x):
19
+ return super().forward(x.float()).type(x.dtype)
20
+
21
+
22
+ def conv_nd(dims, *args, **kwargs):
23
+ """
24
+ Create a 1D, 2D, or 3D convolution module.
25
+ """
26
+ if dims == 1:
27
+ return nn.Conv1d(*args, **kwargs)
28
+ elif dims == 2:
29
+ return nn.Conv2d(*args, **kwargs)
30
+ elif dims == 3:
31
+ return nn.Conv3d(*args, **kwargs)
32
+ raise ValueError(f"unsupported dimensions: {dims}")
33
+
34
+
35
+ def linear(*args, **kwargs):
36
+ """
37
+ Create a linear module.
38
+ """
39
+ return nn.Linear(*args, **kwargs)
40
+
41
+
42
+ def avg_pool_nd(dims, *args, **kwargs):
43
+ """
44
+ Create a 1D, 2D, or 3D average pooling module.
45
+ """
46
+ if dims == 1:
47
+ return nn.AvgPool1d(*args, **kwargs)
48
+ elif dims == 2:
49
+ return nn.AvgPool2d(*args, **kwargs)
50
+ elif dims == 3:
51
+ return nn.AvgPool3d(*args, **kwargs)
52
+ raise ValueError(f"unsupported dimensions: {dims}")
53
+
54
+
55
+ def update_ema(target_params, source_params, rate=0.99):
56
+ """
57
+ Update target parameters to be closer to those of source parameters using
58
+ an exponential moving average.
59
+
60
+ :param target_params: the target parameter sequence.
61
+ :param source_params: the source parameter sequence.
62
+ :param rate: the EMA rate (closer to 1 means slower).
63
+ """
64
+ for targ, src in zip(target_params, source_params):
65
+ targ.detach().mul_(rate).add_(src, alpha=1 - rate)
66
+
67
+
68
+ def zero_module(module):
69
+ """
70
+ Zero out the parameters of a module and return it.
71
+ """
72
+ for p in module.parameters():
73
+ p.detach().zero_()
74
+ return module
75
+
76
+
77
+ def scale_module(module, scale):
78
+ """
79
+ Scale the parameters of a module and return it.
80
+ """
81
+ for p in module.parameters():
82
+ p.detach().mul_(scale)
83
+ return module
84
+
85
+
86
+ def mean_flat(tensor):
87
+ """
88
+ Take the mean over all non-batch dimensions.
89
+ """
90
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
91
+
92
+
93
+ def normalization(channels):
94
+ """
95
+ Make a standard normalization layer.
96
+
97
+ :param channels: number of input channels.
98
+ :return: an nn.Module for normalization.
99
+ """
100
+ return GroupNorm32(32, channels)
101
+
102
+
103
+ def timestep_embedding(timesteps, dim, max_period=10000):
104
+ """
105
+ Create sinusoidal timestep embeddings.
106
+
107
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
108
+ These may be fractional.
109
+ :param dim: the dimension of the output.
110
+ :param max_period: controls the minimum frequency of the embeddings.
111
+ :return: an [N x dim] Tensor of positional embeddings.
112
+ """
113
+ half = dim // 2
114
+ freqs = th.exp(
115
+ -math.log(max_period) * th.arange(start=0, end=half, dtype=th.float32) / half
116
+ ).to(device=timesteps.device)
117
+ args = timesteps[:, None].float() * freqs[None]
118
+ embedding = th.cat([th.cos(args), th.sin(args)], dim=-1)
119
+ if dim % 2:
120
+ embedding = th.cat([embedding, th.zeros_like(embedding[:, :1])], dim=-1)
121
+ return embedding
122
+
123
+
124
+ def checkpoint(func, inputs, params, flag):
125
+ """
126
+ Evaluate a function without caching intermediate activations, allowing for
127
+ reduced memory at the expense of extra compute in the backward pass.
128
+
129
+ :param func: the function to evaluate.
130
+ :param inputs: the argument sequence to pass to `func`.
131
+ :param params: a sequence of parameters `func` depends on but does not
132
+ explicitly take as arguments.
133
+ :param flag: if False, disable gradient checkpointing.
134
+ """
135
+ if flag:
136
+ args = tuple(inputs) + tuple(params)
137
+ return CheckpointFunction.apply(func, len(inputs), *args)
138
+ else:
139
+ return func(*inputs)
140
+
141
+
142
+ class CheckpointFunction(th.autograd.Function):
143
+ @staticmethod
144
+ def forward(ctx, run_function, length, *args):
145
+ ctx.run_function = run_function
146
+ ctx.input_tensors = list(args[:length])
147
+ ctx.input_params = list(args[length:])
148
+ with th.no_grad():
149
+ output_tensors = ctx.run_function(*ctx.input_tensors)
150
+ return output_tensors
151
+
152
+ @staticmethod
153
+ def backward(ctx, *output_grads):
154
+ ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
155
+ with th.enable_grad():
156
+ # Fixes a bug where the first op in run_function modifies the
157
+ # Tensor storage in place, which is not allowed for detach()'d
158
+ # Tensors.
159
+ shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
160
+ output_tensors = ctx.run_function(*shallow_copies)
161
+ input_grads = th.autograd.grad(
162
+ output_tensors,
163
+ ctx.input_tensors + ctx.input_params,
164
+ output_grads,
165
+ allow_unused=True,
166
+ )
167
+ del ctx.input_tensors
168
+ del ctx.input_params
169
+ del output_tensors
170
+ return (None, None) + input_grads
guided_diffusion/guided_diffusion/resample.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+
3
+ import numpy as np
4
+ import torch as th
5
+ import torch.distributed as dist
6
+
7
+
8
+ def create_named_schedule_sampler(name, diffusion):
9
+ """
10
+ Create a ScheduleSampler from a library of pre-defined samplers.
11
+
12
+ :param name: the name of the sampler.
13
+ :param diffusion: the diffusion object to sample for.
14
+ """
15
+ if name == "uniform":
16
+ return UniformSampler(diffusion)
17
+ elif name == "loss-second-moment":
18
+ return LossSecondMomentResampler(diffusion)
19
+ else:
20
+ raise NotImplementedError(f"unknown schedule sampler: {name}")
21
+
22
+
23
+ class ScheduleSampler(ABC):
24
+ """
25
+ A distribution over timesteps in the diffusion process, intended to reduce
26
+ variance of the objective.
27
+
28
+ By default, samplers perform unbiased importance sampling, in which the
29
+ objective's mean is unchanged.
30
+ However, subclasses may override sample() to change how the resampled
31
+ terms are reweighted, allowing for actual changes in the objective.
32
+ """
33
+
34
+ @abstractmethod
35
+ def weights(self):
36
+ """
37
+ Get a numpy array of weights, one per diffusion step.
38
+
39
+ The weights needn't be normalized, but must be positive.
40
+ """
41
+
42
+ def sample(self, batch_size, device):
43
+ """
44
+ Importance-sample timesteps for a batch.
45
+
46
+ :param batch_size: the number of timesteps.
47
+ :param device: the torch device to save to.
48
+ :return: a tuple (timesteps, weights):
49
+ - timesteps: a tensor of timestep indices.
50
+ - weights: a tensor of weights to scale the resulting losses.
51
+ """
52
+ w = self.weights()
53
+ p = w / np.sum(w)
54
+ indices_np = np.random.choice(len(p), size=(batch_size,), p=p)
55
+ indices = th.from_numpy(indices_np).long().to(device)
56
+ weights_np = 1 / (len(p) * p[indices_np])
57
+ weights = th.from_numpy(weights_np).float().to(device)
58
+ return indices, weights
59
+
60
+
61
+ class UniformSampler(ScheduleSampler):
62
+ def __init__(self, diffusion):
63
+ self.diffusion = diffusion
64
+ self._weights = np.ones([diffusion.num_timesteps])
65
+
66
+ def weights(self):
67
+ return self._weights
68
+
69
+
70
+ class LossAwareSampler(ScheduleSampler):
71
+ def update_with_local_losses(self, local_ts, local_losses):
72
+ """
73
+ Update the reweighting using losses from a model.
74
+
75
+ Call this method from each rank with a batch of timesteps and the
76
+ corresponding losses for each of those timesteps.
77
+ This method will perform synchronization to make sure all of the ranks
78
+ maintain the exact same reweighting.
79
+
80
+ :param local_ts: an integer Tensor of timesteps.
81
+ :param local_losses: a 1D Tensor of losses.
82
+ """
83
+ batch_sizes = [
84
+ th.tensor([0], dtype=th.int32, device=local_ts.device)
85
+ for _ in range(dist.get_world_size())
86
+ ]
87
+ dist.all_gather(
88
+ batch_sizes,
89
+ th.tensor([len(local_ts)], dtype=th.int32, device=local_ts.device),
90
+ )
91
+
92
+ # Pad all_gather batches to be the maximum batch size.
93
+ batch_sizes = [x.item() for x in batch_sizes]
94
+ max_bs = max(batch_sizes)
95
+
96
+ timestep_batches = [th.zeros(max_bs).to(local_ts) for bs in batch_sizes]
97
+ loss_batches = [th.zeros(max_bs).to(local_losses) for bs in batch_sizes]
98
+ dist.all_gather(timestep_batches, local_ts)
99
+ dist.all_gather(loss_batches, local_losses)
100
+ timesteps = [
101
+ x.item() for y, bs in zip(timestep_batches, batch_sizes) for x in y[:bs]
102
+ ]
103
+ losses = [x.item() for y, bs in zip(loss_batches, batch_sizes) for x in y[:bs]]
104
+ self.update_with_all_losses(timesteps, losses)
105
+
106
+ @abstractmethod
107
+ def update_with_all_losses(self, ts, losses):
108
+ """
109
+ Update the reweighting using losses from a model.
110
+
111
+ Sub-classes should override this method to update the reweighting
112
+ using losses from the model.
113
+
114
+ This method directly updates the reweighting without synchronizing
115
+ between workers. It is called by update_with_local_losses from all
116
+ ranks with identical arguments. Thus, it should have deterministic
117
+ behavior to maintain state across workers.
118
+
119
+ :param ts: a list of int timesteps.
120
+ :param losses: a list of float losses, one per timestep.
121
+ """
122
+
123
+
124
+ class LossSecondMomentResampler(LossAwareSampler):
125
+ def __init__(self, diffusion, history_per_term=10, uniform_prob=0.001):
126
+ self.diffusion = diffusion
127
+ self.history_per_term = history_per_term
128
+ self.uniform_prob = uniform_prob
129
+ self._loss_history = np.zeros(
130
+ [diffusion.num_timesteps, history_per_term], dtype=np.float64
131
+ )
132
+ self._loss_counts = np.zeros([diffusion.num_timesteps], dtype=np.int)
133
+
134
+ def weights(self):
135
+ if not self._warmed_up():
136
+ return np.ones([self.diffusion.num_timesteps], dtype=np.float64)
137
+ weights = np.sqrt(np.mean(self._loss_history ** 2, axis=-1))
138
+ weights /= np.sum(weights)
139
+ weights *= 1 - self.uniform_prob
140
+ weights += self.uniform_prob / len(weights)
141
+ return weights
142
+
143
+ def update_with_all_losses(self, ts, losses):
144
+ for t, loss in zip(ts, losses):
145
+ if self._loss_counts[t] == self.history_per_term:
146
+ # Shift out the oldest loss term.
147
+ self._loss_history[t, :-1] = self._loss_history[t, 1:]
148
+ self._loss_history[t, -1] = loss
149
+ else:
150
+ self._loss_history[t, self._loss_counts[t]] = loss
151
+ self._loss_counts[t] += 1
152
+
153
+ def _warmed_up(self):
154
+ return (self._loss_counts == self.history_per_term).all()
guided_diffusion/guided_diffusion/respace.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch as th
3
+
4
+ from .gaussian_diffusion import GaussianDiffusion
5
+
6
+
7
+ def space_timesteps(num_timesteps, section_counts):
8
+ """
9
+ Create a list of timesteps to use from an original diffusion process,
10
+ given the number of timesteps we want to take from equally-sized portions
11
+ of the original process.
12
+
13
+ For example, if there's 300 timesteps and the section counts are [10,15,20]
14
+ then the first 100 timesteps are strided to be 10 timesteps, the second 100
15
+ are strided to be 15 timesteps, and the final 100 are strided to be 20.
16
+
17
+ If the stride is a string starting with "ddim", then the fixed striding
18
+ from the DDIM paper is used, and only one section is allowed.
19
+
20
+ :param num_timesteps: the number of diffusion steps in the original
21
+ process to divide up.
22
+ :param section_counts: either a list of numbers, or a string containing
23
+ comma-separated numbers, indicating the step count
24
+ per section. As a special case, use "ddimN" where N
25
+ is a number of steps to use the striding from the
26
+ DDIM paper.
27
+ :return: a set of diffusion steps from the original process to use.
28
+ """
29
+ if isinstance(section_counts, str):
30
+ if section_counts.startswith("ddim"):
31
+ desired_count = int(section_counts[len("ddim") :])
32
+ for i in range(1, num_timesteps):
33
+ if len(range(0, num_timesteps, i)) == desired_count:
34
+ return set(range(0, num_timesteps, i))
35
+ raise ValueError(
36
+ f"cannot create exactly {num_timesteps} steps with an integer stride"
37
+ )
38
+ section_counts = [int(x) for x in section_counts.split(",")]
39
+ size_per = num_timesteps // len(section_counts)
40
+ extra = num_timesteps % len(section_counts)
41
+ start_idx = 0
42
+ all_steps = []
43
+ for i, section_count in enumerate(section_counts):
44
+ size = size_per + (1 if i < extra else 0)
45
+ if size < section_count:
46
+ raise ValueError(
47
+ f"cannot divide section of {size} steps into {section_count}"
48
+ )
49
+ if section_count <= 1:
50
+ frac_stride = 1
51
+ else:
52
+ frac_stride = (size - 1) / (section_count - 1)
53
+ cur_idx = 0.0
54
+ taken_steps = []
55
+ for _ in range(section_count):
56
+ taken_steps.append(start_idx + round(cur_idx))
57
+ cur_idx += frac_stride
58
+ all_steps += taken_steps
59
+ start_idx += size
60
+ return set(all_steps)
61
+
62
+
63
+ class SpacedDiffusion(GaussianDiffusion):
64
+ """
65
+ A diffusion process which can skip steps in a base diffusion process.
66
+
67
+ :param use_timesteps: a collection (sequence or set) of timesteps from the
68
+ original diffusion process to retain.
69
+ :param kwargs: the kwargs to create the base diffusion process.
70
+ """
71
+
72
+ def __init__(self, use_timesteps, **kwargs):
73
+ self.use_timesteps = set(use_timesteps)
74
+ self.timestep_map = []
75
+ self.original_num_steps = len(kwargs["betas"])
76
+
77
+ base_diffusion = GaussianDiffusion(**kwargs) # pylint: disable=missing-kwoa
78
+ last_alpha_cumprod = 1.0
79
+ new_betas = []
80
+ for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod):
81
+ if i in self.use_timesteps:
82
+ new_betas.append(1 - alpha_cumprod / last_alpha_cumprod)
83
+ last_alpha_cumprod = alpha_cumprod
84
+ self.timestep_map.append(i)
85
+ kwargs["betas"] = np.array(new_betas)
86
+ super().__init__(**kwargs)
87
+
88
+ def p_mean_variance(
89
+ self, model, *args, **kwargs
90
+ ): # pylint: disable=signature-differs
91
+ return super().p_mean_variance(self._wrap_model(model), *args, **kwargs)
92
+
93
+ def training_losses(
94
+ self, model, *args, **kwargs
95
+ ): # pylint: disable=signature-differs
96
+ return super().training_losses(self._wrap_model(model), *args, **kwargs)
97
+
98
+ def condition_mean(self, cond_fn, *args, **kwargs):
99
+ return super().condition_mean(self._wrap_model(cond_fn), *args, **kwargs)
100
+
101
+ def condition_score(self, cond_fn, *args, **kwargs):
102
+ return super().condition_score(self._wrap_model(cond_fn), *args, **kwargs)
103
+
104
+ def _wrap_model(self, model):
105
+ if isinstance(model, _WrappedModel):
106
+ return model
107
+ return _WrappedModel(
108
+ model, self.timestep_map, self.rescale_timesteps, self.original_num_steps
109
+ )
110
+
111
+ def _scale_timesteps(self, t):
112
+ # Scaling is done by the wrapped model.
113
+ return t
114
+
115
+
116
+ class _WrappedModel:
117
+ def __init__(self, model, timestep_map, rescale_timesteps, original_num_steps):
118
+ self.model = model
119
+ self.timestep_map = timestep_map
120
+ self.rescale_timesteps = rescale_timesteps
121
+ self.original_num_steps = original_num_steps
122
+
123
+ def __call__(self, x, ts, **kwargs):
124
+ map_tensor = th.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype)
125
+ new_ts = map_tensor[ts]
126
+ if self.rescale_timesteps:
127
+ new_ts = new_ts.float() * (1000.0 / self.original_num_steps)
128
+ return self.model(x, new_ts, **kwargs)
guided_diffusion/guided_diffusion/script_util.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import inspect
3
+
4
+ from . import gaussian_diffusion as gd
5
+ from .respace import SpacedDiffusion, space_timesteps
6
+ from .unet import SuperResModel, UNetModel, EncoderUNetModel
7
+
8
+ NUM_CLASSES = 1000
9
+
10
+
11
+ def diffusion_defaults():
12
+ """
13
+ Defaults for image and classifier training.
14
+ """
15
+ return dict(
16
+ learn_sigma=False,
17
+ diffusion_steps=1000,
18
+ noise_schedule="linear",
19
+ timestep_respacing="",
20
+ use_kl=False,
21
+ predict_xstart=False,
22
+ rescale_timesteps=False,
23
+ rescale_learned_sigmas=False,
24
+ )
25
+
26
+
27
+
28
+ def classifier_defaults():
29
+ """
30
+ Defaults for classifier models.
31
+ """
32
+ return dict(
33
+ image_size=64,
34
+ classifier_use_fp16=False,
35
+ classifier_width=128,
36
+ classifier_depth=2,
37
+ classifier_attention_resolutions="32,16,8", # 16
38
+ classifier_use_scale_shift_norm=True, # False
39
+ classifier_resblock_updown=True, # False
40
+ classifier_pool="attention",
41
+ )
42
+
43
+ def model_and_diffusion_defaults():
44
+ """
45
+ Defaults for image training.
46
+ """
47
+ res = dict(
48
+ image_size=64,
49
+ num_channels=128,
50
+ num_res_blocks=2,
51
+ num_heads=4,
52
+ num_heads_upsample=-1,
53
+ num_head_channels=-1,
54
+ attention_resolutions="16,8",
55
+ channel_mult="",
56
+ dropout=0.0,
57
+ class_cond=False,
58
+ use_checkpoint=False,
59
+ use_scale_shift_norm=True,
60
+ resblock_updown=False,
61
+ use_fp16=False,
62
+ use_new_attention_order=False,
63
+ )
64
+ res.update(diffusion_defaults())
65
+ return res
66
+
67
+
68
+
69
+ def classifier_and_diffusion_defaults():
70
+ res = classifier_defaults()
71
+ res.update(diffusion_defaults())
72
+ return res
73
+
74
+
75
+ def create_model_and_diffusion(
76
+ image_size,
77
+ class_cond,
78
+ learn_sigma,
79
+ num_channels,
80
+ num_res_blocks,
81
+ channel_mult,
82
+ num_heads,
83
+ num_head_channels,
84
+ num_heads_upsample,
85
+ attention_resolutions,
86
+ dropout,
87
+ diffusion_steps,
88
+ noise_schedule,
89
+ timestep_respacing,
90
+ use_kl,
91
+ predict_xstart,
92
+ rescale_timesteps,
93
+ rescale_learned_sigmas,
94
+ use_checkpoint,
95
+ use_scale_shift_norm,
96
+ resblock_updown,
97
+ use_fp16,
98
+ use_new_attention_order,
99
+ ):
100
+ model = create_model(
101
+ image_size,
102
+ num_channels,
103
+ num_res_blocks,
104
+ channel_mult=channel_mult,
105
+ learn_sigma=learn_sigma,
106
+ class_cond=class_cond,
107
+ use_checkpoint=use_checkpoint,
108
+ attention_resolutions=attention_resolutions,
109
+ num_heads=num_heads,
110
+ num_head_channels=num_head_channels,
111
+ num_heads_upsample=num_heads_upsample,
112
+ use_scale_shift_norm=use_scale_shift_norm,
113
+ dropout=dropout,
114
+ resblock_updown=resblock_updown,
115
+ use_fp16=use_fp16,
116
+ use_new_attention_order=use_new_attention_order,
117
+ )
118
+ diffusion = create_gaussian_diffusion(
119
+ steps=diffusion_steps,
120
+ learn_sigma=learn_sigma,
121
+ noise_schedule=noise_schedule,
122
+ use_kl=use_kl,
123
+ predict_xstart=predict_xstart,
124
+ rescale_timesteps=rescale_timesteps,
125
+ rescale_learned_sigmas=rescale_learned_sigmas,
126
+ timestep_respacing=timestep_respacing,
127
+ )
128
+ return model, diffusion
129
+
130
+
131
+ def create_model(
132
+ image_size,
133
+ num_channels,
134
+ num_res_blocks,
135
+ channel_mult="",
136
+ learn_sigma=False,
137
+ class_cond=False,
138
+ use_checkpoint=False,
139
+ attention_resolutions="16",
140
+ num_heads=1,
141
+ num_head_channels=-1,
142
+ num_heads_upsample=-1,
143
+ use_scale_shift_norm=False,
144
+ dropout=0,
145
+ resblock_updown=False,
146
+ use_fp16=False,
147
+ use_new_attention_order=False,
148
+ ):
149
+ if channel_mult == "":
150
+ if image_size == 512:
151
+ channel_mult = (0.5, 1, 1, 2, 2, 4, 4)
152
+ elif image_size == 256:
153
+ channel_mult = (1, 1, 2, 2, 4, 4)
154
+ elif image_size == 128:
155
+ channel_mult = (1, 1, 2, 3, 4)
156
+ elif image_size == 64:
157
+ channel_mult = (1, 2, 3, 4)
158
+ else:
159
+ raise ValueError(f"unsupported image size: {image_size}")
160
+ else:
161
+ channel_mult = tuple(int(ch_mult) for ch_mult in channel_mult.split(","))
162
+
163
+ attention_ds = []
164
+ for res in attention_resolutions.split(","):
165
+ attention_ds.append(image_size // int(res))
166
+
167
+ return UNetModel(
168
+ image_size=image_size,
169
+ in_channels=3,
170
+ model_channels=num_channels,
171
+ out_channels=(3 if not learn_sigma else 6),
172
+ num_res_blocks=num_res_blocks,
173
+ attention_resolutions=tuple(attention_ds),
174
+ dropout=dropout,
175
+ channel_mult=channel_mult,
176
+ num_classes=(NUM_CLASSES if class_cond else None),
177
+ use_checkpoint=use_checkpoint,
178
+ use_fp16=use_fp16,
179
+ num_heads=num_heads,
180
+ num_head_channels=num_head_channels,
181
+ num_heads_upsample=num_heads_upsample,
182
+ use_scale_shift_norm=use_scale_shift_norm,
183
+ resblock_updown=resblock_updown,
184
+ use_new_attention_order=use_new_attention_order,
185
+ )
186
+
187
+
188
+ def create_classifier_and_diffusion(
189
+ image_size,
190
+ classifier_use_fp16,
191
+ classifier_width,
192
+ classifier_depth,
193
+ classifier_attention_resolutions,
194
+ classifier_use_scale_shift_norm,
195
+ classifier_resblock_updown,
196
+ classifier_pool,
197
+ learn_sigma,
198
+ diffusion_steps,
199
+ noise_schedule,
200
+ timestep_respacing,
201
+ use_kl,
202
+ predict_xstart,
203
+ rescale_timesteps,
204
+ rescale_learned_sigmas,
205
+ ):
206
+ classifier = create_classifier(
207
+ image_size,
208
+ classifier_use_fp16,
209
+ classifier_width,
210
+ classifier_depth,
211
+ classifier_attention_resolutions,
212
+ classifier_use_scale_shift_norm,
213
+ classifier_resblock_updown,
214
+ classifier_pool,
215
+ )
216
+ diffusion = create_gaussian_diffusion(
217
+ steps=diffusion_steps,
218
+ learn_sigma=learn_sigma,
219
+ noise_schedule=noise_schedule,
220
+ use_kl=use_kl,
221
+ predict_xstart=predict_xstart,
222
+ rescale_timesteps=rescale_timesteps,
223
+ rescale_learned_sigmas=rescale_learned_sigmas,
224
+ timestep_respacing=timestep_respacing,
225
+ )
226
+ return classifier, diffusion
227
+
228
+
229
+ def create_classifier(
230
+ image_size,
231
+ classifier_use_fp16,
232
+ classifier_width,
233
+ classifier_depth,
234
+ classifier_attention_resolutions,
235
+ classifier_use_scale_shift_norm,
236
+ classifier_resblock_updown,
237
+ classifier_pool,
238
+ ):
239
+ if image_size == 512:
240
+ channel_mult = (0.5, 1, 1, 2, 2, 4, 4)
241
+ elif image_size == 256:
242
+ channel_mult = (1, 1, 2, 2, 4, 4)
243
+ elif image_size == 128:
244
+ channel_mult = (1, 1, 2, 3, 4)
245
+ elif image_size == 64:
246
+ channel_mult = (1, 2, 3, 4)
247
+ else:
248
+ raise ValueError(f"unsupported image size: {image_size}")
249
+
250
+ attention_ds = []
251
+ for res in classifier_attention_resolutions.split(","):
252
+ attention_ds.append(image_size // int(res))
253
+
254
+ return EncoderUNetModel(
255
+ image_size=image_size,
256
+ in_channels=3,
257
+ model_channels=classifier_width,
258
+ out_channels=1000,
259
+ num_res_blocks=classifier_depth,
260
+ attention_resolutions=tuple(attention_ds),
261
+ channel_mult=channel_mult,
262
+ use_fp16=classifier_use_fp16,
263
+ num_head_channels=64,
264
+ use_scale_shift_norm=classifier_use_scale_shift_norm,
265
+ resblock_updown=classifier_resblock_updown,
266
+ pool=classifier_pool,
267
+ )
268
+
269
+
270
+ def sr_model_and_diffusion_defaults():
271
+ res = model_and_diffusion_defaults()
272
+ res["large_size"] = 256
273
+ res["small_size"] = 64
274
+ arg_names = inspect.getfullargspec(sr_create_model_and_diffusion)[0]
275
+ for k in res.copy().keys():
276
+ if k not in arg_names:
277
+ del res[k]
278
+ return res
279
+
280
+
281
+ def sr_create_model_and_diffusion(
282
+ large_size,
283
+ small_size,
284
+ class_cond,
285
+ learn_sigma,
286
+ num_channels,
287
+ num_res_blocks,
288
+ num_heads,
289
+ num_head_channels,
290
+ num_heads_upsample,
291
+ attention_resolutions,
292
+ dropout,
293
+ diffusion_steps,
294
+ noise_schedule,
295
+ timestep_respacing,
296
+ use_kl,
297
+ predict_xstart,
298
+ rescale_timesteps,
299
+ rescale_learned_sigmas,
300
+ use_checkpoint,
301
+ use_scale_shift_norm,
302
+ resblock_updown,
303
+ use_fp16,
304
+ ):
305
+ model = sr_create_model(
306
+ large_size,
307
+ small_size,
308
+ num_channels,
309
+ num_res_blocks,
310
+ learn_sigma=learn_sigma,
311
+ class_cond=class_cond,
312
+ use_checkpoint=use_checkpoint,
313
+ attention_resolutions=attention_resolutions,
314
+ num_heads=num_heads,
315
+ num_head_channels=num_head_channels,
316
+ num_heads_upsample=num_heads_upsample,
317
+ use_scale_shift_norm=use_scale_shift_norm,
318
+ dropout=dropout,
319
+ resblock_updown=resblock_updown,
320
+ use_fp16=use_fp16,
321
+ )
322
+ diffusion = create_gaussian_diffusion(
323
+ steps=diffusion_steps,
324
+ learn_sigma=learn_sigma,
325
+ noise_schedule=noise_schedule,
326
+ use_kl=use_kl,
327
+ predict_xstart=predict_xstart,
328
+ rescale_timesteps=rescale_timesteps,
329
+ rescale_learned_sigmas=rescale_learned_sigmas,
330
+ timestep_respacing=timestep_respacing,
331
+ )
332
+ return model, diffusion
333
+
334
+
335
+ def sr_create_model(
336
+ large_size,
337
+ small_size,
338
+ num_channels,
339
+ num_res_blocks,
340
+ learn_sigma,
341
+ class_cond,
342
+ use_checkpoint,
343
+ attention_resolutions,
344
+ num_heads,
345
+ num_head_channels,
346
+ num_heads_upsample,
347
+ use_scale_shift_norm,
348
+ dropout,
349
+ resblock_updown,
350
+ use_fp16,
351
+ ):
352
+ _ = small_size # hack to prevent unused variable
353
+
354
+ if large_size == 512:
355
+ channel_mult = (1, 1, 2, 2, 4, 4)
356
+ elif large_size == 256:
357
+ channel_mult = (1, 1, 2, 2, 4, 4)
358
+ elif large_size == 64:
359
+ channel_mult = (1, 2, 3, 4)
360
+ else:
361
+ raise ValueError(f"unsupported large size: {large_size}")
362
+
363
+ attention_ds = []
364
+ for res in attention_resolutions.split(","):
365
+ attention_ds.append(large_size // int(res))
366
+
367
+ return SuperResModel(
368
+ image_size=large_size,
369
+ in_channels=3,
370
+ model_channels=num_channels,
371
+ out_channels=(3 if not learn_sigma else 6),
372
+ num_res_blocks=num_res_blocks,
373
+ attention_resolutions=tuple(attention_ds),
374
+ dropout=dropout,
375
+ channel_mult=channel_mult,
376
+ num_classes=(NUM_CLASSES if class_cond else None),
377
+ use_checkpoint=use_checkpoint,
378
+ num_heads=num_heads,
379
+ num_head_channels=num_head_channels,
380
+ num_heads_upsample=num_heads_upsample,
381
+ use_scale_shift_norm=use_scale_shift_norm,
382
+ resblock_updown=resblock_updown,
383
+ use_fp16=use_fp16,
384
+ )
385
+
386
+
387
+ def create_gaussian_diffusion(
388
+ *,
389
+ steps=1000,
390
+ learn_sigma=False,
391
+ sigma_small=False,
392
+ noise_schedule="linear",
393
+ use_kl=False,
394
+ predict_xstart=False,
395
+ rescale_timesteps=False,
396
+ rescale_learned_sigmas=False,
397
+ timestep_respacing="",
398
+ ):
399
+ betas = gd.get_named_beta_schedule(noise_schedule, steps)
400
+ if use_kl:
401
+ loss_type = gd.LossType.RESCALED_KL
402
+ elif rescale_learned_sigmas:
403
+ loss_type = gd.LossType.RESCALED_MSE
404
+ else:
405
+ loss_type = gd.LossType.MSE
406
+ if not timestep_respacing:
407
+ timestep_respacing = [steps]
408
+ return SpacedDiffusion(
409
+ use_timesteps=space_timesteps(steps, timestep_respacing),
410
+ betas=betas,
411
+ model_mean_type=(
412
+ gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X
413
+ ),
414
+ model_var_type=(
415
+ (
416
+ gd.ModelVarType.FIXED_LARGE
417
+ if not sigma_small
418
+ else gd.ModelVarType.FIXED_SMALL
419
+ )
420
+ if not learn_sigma
421
+ else gd.ModelVarType.LEARNED_RANGE
422
+ ),
423
+ loss_type=loss_type,
424
+ rescale_timesteps=rescale_timesteps,
425
+ )
426
+
427
+
428
+ def add_dict_to_argparser(parser, default_dict):
429
+ for k, v in default_dict.items():
430
+ v_type = type(v)
431
+ if v is None:
432
+ v_type = str
433
+ elif isinstance(v, bool):
434
+ v_type = str2bool
435
+ parser.add_argument(f"--{k}", default=v, type=v_type)
436
+
437
+
438
+ def args_to_dict(args, keys):
439
+ return {k: getattr(args, k) for k in keys}
440
+
441
+ def dict_parse(args, keys):
442
+ return {k: args[k] for k in keys}
443
+
444
+
445
+ def str2bool(v):
446
+ """
447
+ https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
448
+ """
449
+ if isinstance(v, bool):
450
+ return v
451
+ if v.lower() in ("yes", "true", "t", "y", "1"):
452
+ return True
453
+ elif v.lower() in ("no", "false", "f", "n", "0"):
454
+ return False
455
+ else:
456
+ raise argparse.ArgumentTypeError("boolean value expected")
guided_diffusion/guided_diffusion/train_util.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import functools
3
+ import os
4
+
5
+ import blobfile as bf
6
+ import torch as th
7
+ import torch.distributed as dist
8
+ from torch.nn.parallel.distributed import DistributedDataParallel as DDP
9
+ from torch.optim import AdamW
10
+
11
+ from . import dist_util, logger
12
+ from .fp16_util import MixedPrecisionTrainer
13
+ from .nn import update_ema
14
+ from .resample import LossAwareSampler, UniformSampler
15
+
16
+ # For ImageNet experiments, this was a good default value.
17
+ # We found that the lg_loss_scale quickly climbed to
18
+ # 20-21 within the first ~1K steps of training.
19
+ INITIAL_LOG_LOSS_SCALE = 20.0
20
+
21
+
22
+ class TrainLoop:
23
+ def __init__(
24
+ self,
25
+ *,
26
+ model,
27
+ diffusion,
28
+ data,
29
+ batch_size,
30
+ microbatch,
31
+ lr,
32
+ ema_rate,
33
+ log_interval,
34
+ save_interval,
35
+ resume_checkpoint,
36
+ use_fp16=False,
37
+ fp16_scale_growth=1e-3,
38
+ schedule_sampler=None,
39
+ weight_decay=0.0,
40
+ lr_anneal_steps=0,
41
+ ):
42
+ self.model = model
43
+ self.diffusion = diffusion
44
+ self.data = data
45
+ self.batch_size = batch_size
46
+ self.microbatch = microbatch if microbatch > 0 else batch_size
47
+ self.lr = lr
48
+ self.ema_rate = (
49
+ [ema_rate]
50
+ if isinstance(ema_rate, float)
51
+ else [float(x) for x in ema_rate.split(",")]
52
+ )
53
+ self.log_interval = log_interval
54
+ self.save_interval = save_interval
55
+ self.resume_checkpoint = resume_checkpoint
56
+ self.use_fp16 = use_fp16
57
+ self.fp16_scale_growth = fp16_scale_growth
58
+ self.schedule_sampler = schedule_sampler or UniformSampler(diffusion)
59
+ self.weight_decay = weight_decay
60
+ self.lr_anneal_steps = lr_anneal_steps
61
+
62
+ self.step = 0
63
+ self.resume_step = 0
64
+ self.global_batch = self.batch_size * dist.get_world_size()
65
+
66
+ self.sync_cuda = th.cuda.is_available()
67
+
68
+ self._load_and_sync_parameters()
69
+ self.mp_trainer = MixedPrecisionTrainer(
70
+ model=self.model,
71
+ use_fp16=self.use_fp16,
72
+ fp16_scale_growth=fp16_scale_growth,
73
+ )
74
+
75
+ self.opt = AdamW(
76
+ self.mp_trainer.master_params, lr=self.lr, weight_decay=self.weight_decay
77
+ )
78
+ if self.resume_step:
79
+ self._load_optimizer_state()
80
+ # Model was resumed, either due to a restart or a checkpoint
81
+ # being specified at the command line.
82
+ self.ema_params = [
83
+ self._load_ema_parameters(rate) for rate in self.ema_rate
84
+ ]
85
+ else:
86
+ self.ema_params = [
87
+ copy.deepcopy(self.mp_trainer.master_params)
88
+ for _ in range(len(self.ema_rate))
89
+ ]
90
+
91
+ if th.cuda.is_available():
92
+ self.use_ddp = True
93
+ self.ddp_model = DDP(
94
+ self.model,
95
+ device_ids=[dist_util.dev()],
96
+ output_device=dist_util.dev(),
97
+ broadcast_buffers=False,
98
+ bucket_cap_mb=128,
99
+ find_unused_parameters=False,
100
+ )
101
+ else:
102
+ if dist.get_world_size() > 1:
103
+ logger.warn(
104
+ "Distributed training requires CUDA. "
105
+ "Gradients will not be synchronized properly!"
106
+ )
107
+ self.use_ddp = False
108
+ self.ddp_model = self.model
109
+
110
+ def _load_and_sync_parameters(self):
111
+ resume_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
112
+
113
+ if resume_checkpoint:
114
+ self.resume_step = parse_resume_step_from_filename(resume_checkpoint)
115
+ if dist.get_rank() == 0:
116
+ logger.log(f"loading model from checkpoint: {resume_checkpoint}...")
117
+ self.model.load_state_dict(
118
+ dist_util.load_state_dict(
119
+ resume_checkpoint, map_location=dist_util.dev()
120
+ )
121
+ )
122
+
123
+ dist_util.sync_params(self.model.parameters())
124
+
125
+ def _load_ema_parameters(self, rate):
126
+ ema_params = copy.deepcopy(self.mp_trainer.master_params)
127
+
128
+ main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
129
+ ema_checkpoint = find_ema_checkpoint(main_checkpoint, self.resume_step, rate)
130
+ if ema_checkpoint:
131
+ if dist.get_rank() == 0:
132
+ logger.log(f"loading EMA from checkpoint: {ema_checkpoint}...")
133
+ state_dict = dist_util.load_state_dict(
134
+ ema_checkpoint, map_location=dist_util.dev()
135
+ )
136
+ ema_params = self.mp_trainer.state_dict_to_master_params(state_dict)
137
+
138
+ dist_util.sync_params(ema_params)
139
+ return ema_params
140
+
141
+ def _load_optimizer_state(self):
142
+ main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
143
+ opt_checkpoint = bf.join(
144
+ bf.dirname(main_checkpoint), f"opt{self.resume_step:06}.pt"
145
+ )
146
+ if bf.exists(opt_checkpoint):
147
+ logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}")
148
+ state_dict = dist_util.load_state_dict(
149
+ opt_checkpoint, map_location=dist_util.dev()
150
+ )
151
+ self.opt.load_state_dict(state_dict)
152
+
153
+ def run_loop(self):
154
+ while (
155
+ not self.lr_anneal_steps
156
+ or self.step + self.resume_step < self.lr_anneal_steps
157
+ ):
158
+ batch, cond = next(self.data)
159
+ self.run_step(batch, cond)
160
+ if self.step % self.log_interval == 0:
161
+ logger.dumpkvs()
162
+ if self.step % self.save_interval == 0:
163
+ self.save()
164
+ # Run for a finite amount of time in integration tests.
165
+ if os.environ.get("DIFFUSION_TRAINING_TEST", "") and self.step > 0:
166
+ return
167
+ self.step += 1
168
+ # Save the last checkpoint if it wasn't already saved.
169
+ if (self.step - 1) % self.save_interval != 0:
170
+ self.save()
171
+
172
+ def run_step(self, batch, cond):
173
+ self.forward_backward(batch, cond)
174
+ took_step = self.mp_trainer.optimize(self.opt)
175
+ if took_step:
176
+ self._update_ema()
177
+ self._anneal_lr()
178
+ self.log_step()
179
+
180
+ def forward_backward(self, batch, cond):
181
+ self.mp_trainer.zero_grad()
182
+ for i in range(0, batch.shape[0], self.microbatch):
183
+ micro = batch[i : i + self.microbatch].to(dist_util.dev())
184
+ micro_cond = {
185
+ k: v[i : i + self.microbatch].to(dist_util.dev())
186
+ for k, v in cond.items()
187
+ }
188
+ last_batch = (i + self.microbatch) >= batch.shape[0]
189
+ t, weights = self.schedule_sampler.sample(micro.shape[0], dist_util.dev())
190
+
191
+ compute_losses = functools.partial(
192
+ self.diffusion.training_losses,
193
+ self.ddp_model,
194
+ micro,
195
+ t,
196
+ model_kwargs=micro_cond,
197
+ )
198
+
199
+ if last_batch or not self.use_ddp:
200
+ losses = compute_losses()
201
+ else:
202
+ with self.ddp_model.no_sync():
203
+ losses = compute_losses()
204
+
205
+ if isinstance(self.schedule_sampler, LossAwareSampler):
206
+ self.schedule_sampler.update_with_local_losses(
207
+ t, losses["loss"].detach()
208
+ )
209
+
210
+ loss = (losses["loss"] * weights).mean()
211
+ log_loss_dict(
212
+ self.diffusion, t, {k: v * weights for k, v in losses.items()}
213
+ )
214
+ self.mp_trainer.backward(loss)
215
+
216
+ def _update_ema(self):
217
+ for rate, params in zip(self.ema_rate, self.ema_params):
218
+ update_ema(params, self.mp_trainer.master_params, rate=rate)
219
+
220
+ def _anneal_lr(self):
221
+ if not self.lr_anneal_steps:
222
+ return
223
+ frac_done = (self.step + self.resume_step) / self.lr_anneal_steps
224
+ lr = self.lr * (1 - frac_done)
225
+ for param_group in self.opt.param_groups:
226
+ param_group["lr"] = lr
227
+
228
+ def log_step(self):
229
+ logger.logkv("step", self.step + self.resume_step)
230
+ logger.logkv("samples", (self.step + self.resume_step + 1) * self.global_batch)
231
+
232
+ def save(self):
233
+ def save_checkpoint(rate, params):
234
+ state_dict = self.mp_trainer.master_params_to_state_dict(params)
235
+ if dist.get_rank() == 0:
236
+ logger.log(f"saving model {rate}...")
237
+ if not rate:
238
+ filename = f"model{(self.step+self.resume_step):06d}.pt"
239
+ else:
240
+ filename = f"ema_{rate}_{(self.step+self.resume_step):06d}.pt"
241
+ with bf.BlobFile(bf.join(get_blob_logdir(), filename), "wb") as f:
242
+ th.save(state_dict, f)
243
+
244
+ save_checkpoint(0, self.mp_trainer.master_params)
245
+ for rate, params in zip(self.ema_rate, self.ema_params):
246
+ save_checkpoint(rate, params)
247
+
248
+ if dist.get_rank() == 0:
249
+ with bf.BlobFile(
250
+ bf.join(get_blob_logdir(), f"opt{(self.step+self.resume_step):06d}.pt"),
251
+ "wb",
252
+ ) as f:
253
+ th.save(self.opt.state_dict(), f)
254
+
255
+ dist.barrier()
256
+
257
+
258
+ def parse_resume_step_from_filename(filename):
259
+ """
260
+ Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the
261
+ checkpoint's number of steps.
262
+ """
263
+ split = filename.split("model")
264
+ if len(split) < 2:
265
+ return 0
266
+ split1 = split[-1].split(".")[0]
267
+ try:
268
+ return int(split1)
269
+ except ValueError:
270
+ return 0
271
+
272
+
273
+ def get_blob_logdir():
274
+ # You can change this to be a separate path to save checkpoints to
275
+ # a blobstore or some external drive.
276
+ return logger.get_dir()
277
+
278
+
279
+ def find_resume_checkpoint():
280
+ # On your infrastructure, you may want to override this to automatically
281
+ # discover the latest checkpoint on your blob storage, etc.
282
+ return None
283
+
284
+
285
+ def find_ema_checkpoint(main_checkpoint, step, rate):
286
+ if main_checkpoint is None:
287
+ return None
288
+ filename = f"ema_{rate}_{(step):06d}.pt"
289
+ path = bf.join(bf.dirname(main_checkpoint), filename)
290
+ if bf.exists(path):
291
+ return path
292
+ return None
293
+
294
+
295
+ def log_loss_dict(diffusion, ts, losses):
296
+ for key, values in losses.items():
297
+ logger.logkv_mean(key, values.mean().item())
298
+ # Log the quantiles (four quartiles, in particular).
299
+ for sub_t, sub_loss in zip(ts.cpu().numpy(), values.detach().cpu().numpy()):
300
+ quartile = int(4 * sub_t / diffusion.num_timesteps)
301
+ logger.logkv_mean(f"{key}_q{quartile}", sub_loss)
guided_diffusion/guided_diffusion/unet.py ADDED
@@ -0,0 +1,897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch as th
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ from .fp16_util import convert_module_to_f16, convert_module_to_f32
11
+ from .nn import (
12
+ checkpoint,
13
+ conv_nd,
14
+ linear,
15
+ avg_pool_nd,
16
+ zero_module,
17
+ normalization,
18
+ timestep_embedding,
19
+ )
20
+
21
+
22
+ class AttentionPool2d(nn.Module):
23
+ """
24
+ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ spacial_dim: int,
30
+ embed_dim: int,
31
+ num_heads_channels: int,
32
+ output_dim: int = None,
33
+ ):
34
+ super().__init__()
35
+ self.positional_embedding = nn.Parameter(
36
+ th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5
37
+ )
38
+ self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
39
+ self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
40
+ self.num_heads = embed_dim // num_heads_channels
41
+ self.attention = QKVAttention(self.num_heads)
42
+
43
+ def forward(self, x):
44
+ b, c, *_spatial = x.shape
45
+ x = x.reshape(b, c, -1) # NC(HW)
46
+ x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
47
+ x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
48
+ x = self.qkv_proj(x)
49
+ x = self.attention(x)
50
+ x = self.c_proj(x)
51
+ return x[:, :, 0]
52
+
53
+
54
+ class TimestepBlock(nn.Module):
55
+ """
56
+ Any module where forward() takes timestep embeddings as a second argument.
57
+ """
58
+
59
+ @abstractmethod
60
+ def forward(self, x, emb):
61
+ """
62
+ Apply the module to `x` given `emb` timestep embeddings.
63
+ """
64
+
65
+
66
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
67
+ """
68
+ A sequential module that passes timestep embeddings to the children that
69
+ support it as an extra input.
70
+ """
71
+
72
+ def forward(self, x, emb):
73
+ for layer in self:
74
+ if isinstance(layer, TimestepBlock):
75
+ x = layer(x, emb)
76
+ else:
77
+ x = layer(x)
78
+ return x
79
+
80
+
81
+ class Upsample(nn.Module):
82
+ """
83
+ An upsampling layer with an optional convolution.
84
+
85
+ :param channels: channels in the inputs and outputs.
86
+ :param use_conv: a bool determining if a convolution is applied.
87
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
88
+ upsampling occurs in the inner-two dimensions.
89
+ """
90
+
91
+ def __init__(self, channels, use_conv, dims=2, out_channels=None):
92
+ super().__init__()
93
+ self.channels = channels
94
+ self.out_channels = out_channels or channels
95
+ self.use_conv = use_conv
96
+ self.dims = dims
97
+ if use_conv:
98
+ self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
99
+
100
+ def forward(self, x):
101
+ assert x.shape[1] == self.channels
102
+ if self.dims == 3:
103
+ x = F.interpolate(
104
+ x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
105
+ )
106
+ else:
107
+ x = F.interpolate(x, scale_factor=2, mode="nearest")
108
+ if self.use_conv:
109
+ x = self.conv(x)
110
+ return x
111
+
112
+
113
+ class Downsample(nn.Module):
114
+ """
115
+ A downsampling layer with an optional convolution.
116
+
117
+ :param channels: channels in the inputs and outputs.
118
+ :param use_conv: a bool determining if a convolution is applied.
119
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
120
+ downsampling occurs in the inner-two dimensions.
121
+ """
122
+
123
+ def __init__(self, channels, use_conv, dims=2, out_channels=None):
124
+ super().__init__()
125
+ self.channels = channels
126
+ self.out_channels = out_channels or channels
127
+ self.use_conv = use_conv
128
+ self.dims = dims
129
+ stride = 2 if dims != 3 else (1, 2, 2)
130
+ if use_conv:
131
+ self.op = conv_nd(
132
+ dims, self.channels, self.out_channels, 3, stride=stride, padding=1
133
+ )
134
+ else:
135
+ assert self.channels == self.out_channels
136
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
137
+
138
+ def forward(self, x):
139
+ assert x.shape[1] == self.channels
140
+ return self.op(x)
141
+
142
+
143
+ class ResBlock(TimestepBlock):
144
+ """
145
+ A residual block that can optionally change the number of channels.
146
+
147
+ :param channels: the number of input channels.
148
+ :param emb_channels: the number of timestep embedding channels.
149
+ :param dropout: the rate of dropout.
150
+ :param out_channels: if specified, the number of out channels.
151
+ :param use_conv: if True and out_channels is specified, use a spatial
152
+ convolution instead of a smaller 1x1 convolution to change the
153
+ channels in the skip connection.
154
+ :param dims: determines if the signal is 1D, 2D, or 3D.
155
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
156
+ :param up: if True, use this block for upsampling.
157
+ :param down: if True, use this block for downsampling.
158
+ """
159
+
160
+ def __init__(
161
+ self,
162
+ channels,
163
+ emb_channels,
164
+ dropout,
165
+ out_channels=None,
166
+ use_conv=False,
167
+ use_scale_shift_norm=False,
168
+ dims=2,
169
+ use_checkpoint=False,
170
+ up=False,
171
+ down=False,
172
+ ):
173
+ super().__init__()
174
+ self.channels = channels
175
+ self.emb_channels = emb_channels
176
+ self.dropout = dropout
177
+ self.out_channels = out_channels or channels
178
+ self.use_conv = use_conv
179
+ self.use_checkpoint = use_checkpoint
180
+ self.use_scale_shift_norm = use_scale_shift_norm
181
+
182
+ self.in_layers = nn.Sequential(
183
+ normalization(channels),
184
+ nn.SiLU(),
185
+ conv_nd(dims, channels, self.out_channels, 3, padding=1),
186
+ )
187
+
188
+ self.updown = up or down
189
+
190
+ if up:
191
+ self.h_upd = Upsample(channels, False, dims)
192
+ self.x_upd = Upsample(channels, False, dims)
193
+ elif down:
194
+ self.h_upd = Downsample(channels, False, dims)
195
+ self.x_upd = Downsample(channels, False, dims)
196
+ else:
197
+ self.h_upd = self.x_upd = nn.Identity()
198
+
199
+ self.emb_layers = nn.Sequential(
200
+ nn.SiLU(),
201
+ linear(
202
+ emb_channels,
203
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
204
+ ),
205
+ )
206
+ self.out_layers = nn.Sequential(
207
+ normalization(self.out_channels),
208
+ nn.SiLU(),
209
+ nn.Dropout(p=dropout),
210
+ zero_module(
211
+ conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
212
+ ),
213
+ )
214
+
215
+ if self.out_channels == channels:
216
+ self.skip_connection = nn.Identity()
217
+ elif use_conv:
218
+ self.skip_connection = conv_nd(
219
+ dims, channels, self.out_channels, 3, padding=1
220
+ )
221
+ else:
222
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
223
+
224
+ def forward(self, x, emb):
225
+ """
226
+ Apply the block to a Tensor, conditioned on a timestep embedding.
227
+
228
+ :param x: an [N x C x ...] Tensor of features.
229
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
230
+ :return: an [N x C x ...] Tensor of outputs.
231
+ """
232
+ return checkpoint(
233
+ self._forward, (x, emb), self.parameters(), self.use_checkpoint
234
+ )
235
+
236
+ def _forward(self, x, emb):
237
+ if self.updown:
238
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
239
+ h = in_rest(x)
240
+ h = self.h_upd(h)
241
+ x = self.x_upd(x)
242
+ h = in_conv(h)
243
+ else:
244
+ h = self.in_layers(x)
245
+ emb_out = self.emb_layers(emb).type(h.dtype)
246
+ while len(emb_out.shape) < len(h.shape):
247
+ emb_out = emb_out[..., None]
248
+ if self.use_scale_shift_norm:
249
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
250
+ scale, shift = th.chunk(emb_out, 2, dim=1)
251
+ h = out_norm(h) * (1 + scale) + shift
252
+ h = out_rest(h)
253
+ else:
254
+ h = h + emb_out
255
+ h = self.out_layers(h)
256
+ return self.skip_connection(x) + h
257
+
258
+
259
+ class AttentionBlock(nn.Module):
260
+ """
261
+ An attention block that allows spatial positions to attend to each other.
262
+
263
+ Originally ported from here, but adapted to the N-d case.
264
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
265
+ """
266
+
267
+ def __init__(
268
+ self,
269
+ channels,
270
+ num_heads=1,
271
+ num_head_channels=-1,
272
+ use_checkpoint=False,
273
+ use_new_attention_order=False,
274
+ ):
275
+ super().__init__()
276
+ self.channels = channels
277
+ if num_head_channels == -1:
278
+ self.num_heads = num_heads
279
+ else:
280
+ assert (
281
+ channels % num_head_channels == 0
282
+ ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
283
+ self.num_heads = channels // num_head_channels
284
+ self.use_checkpoint = use_checkpoint
285
+ self.norm = normalization(channels)
286
+ self.qkv = conv_nd(1, channels, channels * 3, 1)
287
+ if use_new_attention_order:
288
+ # split qkv before split heads
289
+ self.attention = QKVAttention(self.num_heads)
290
+ else:
291
+ # split heads before split qkv
292
+ self.attention = QKVAttentionLegacy(self.num_heads)
293
+
294
+ self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
295
+
296
+ def forward(self, x):
297
+ return checkpoint(self._forward, (x,), self.parameters(), True)
298
+
299
+ def _forward(self, x):
300
+ b, c, *spatial = x.shape
301
+ x = x.reshape(b, c, -1)
302
+ qkv = self.qkv(self.norm(x))
303
+ h = self.attention(qkv)
304
+ h = self.proj_out(h)
305
+ return (x + h).reshape(b, c, *spatial)
306
+
307
+
308
+ def count_flops_attn(model, _x, y):
309
+ """
310
+ A counter for the `thop` package to count the operations in an
311
+ attention operation.
312
+ Meant to be used like:
313
+ macs, params = thop.profile(
314
+ model,
315
+ inputs=(inputs, timestamps),
316
+ custom_ops={QKVAttention: QKVAttention.count_flops},
317
+ )
318
+ """
319
+ b, c, *spatial = y[0].shape
320
+ num_spatial = int(np.prod(spatial))
321
+ # We perform two matmuls with the same number of ops.
322
+ # The first computes the weight matrix, the second computes
323
+ # the combination of the value vectors.
324
+ matmul_ops = 2 * b * (num_spatial ** 2) * c
325
+ model.total_ops += th.DoubleTensor([matmul_ops])
326
+
327
+
328
+ class QKVAttentionLegacy(nn.Module):
329
+ """
330
+ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
331
+ """
332
+
333
+ def __init__(self, n_heads):
334
+ super().__init__()
335
+ self.n_heads = n_heads
336
+
337
+ def forward(self, qkv):
338
+ """
339
+ Apply QKV attention.
340
+
341
+ :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
342
+ :return: an [N x (H * C) x T] tensor after attention.
343
+ """
344
+ bs, width, length = qkv.shape
345
+ assert width % (3 * self.n_heads) == 0
346
+ ch = width // (3 * self.n_heads)
347
+ q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
348
+ scale = 1 / math.sqrt(math.sqrt(ch))
349
+ weight = th.einsum(
350
+ "bct,bcs->bts", q * scale, k * scale
351
+ ) # More stable with f16 than dividing afterwards
352
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
353
+ a = th.einsum("bts,bcs->bct", weight, v)
354
+ return a.reshape(bs, -1, length)
355
+
356
+ @staticmethod
357
+ def count_flops(model, _x, y):
358
+ return count_flops_attn(model, _x, y)
359
+
360
+
361
+ class QKVAttention(nn.Module):
362
+ """
363
+ A module which performs QKV attention and splits in a different order.
364
+ """
365
+
366
+ def __init__(self, n_heads):
367
+ super().__init__()
368
+ self.n_heads = n_heads
369
+
370
+ def forward(self, qkv):
371
+ """
372
+ Apply QKV attention.
373
+
374
+ :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
375
+ :return: an [N x (H * C) x T] tensor after attention.
376
+ """
377
+ bs, width, length = qkv.shape
378
+ assert width % (3 * self.n_heads) == 0
379
+ ch = width // (3 * self.n_heads)
380
+ q, k, v = qkv.chunk(3, dim=1)
381
+ scale = 1 / math.sqrt(math.sqrt(ch))
382
+ weight = th.einsum(
383
+ "bct,bcs->bts",
384
+ (q * scale).view(bs * self.n_heads, ch, length),
385
+ (k * scale).view(bs * self.n_heads, ch, length),
386
+ ) # More stable with f16 than dividing afterwards
387
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
388
+ a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
389
+ return a.reshape(bs, -1, length)
390
+
391
+ @staticmethod
392
+ def count_flops(model, _x, y):
393
+ return count_flops_attn(model, _x, y)
394
+
395
+
396
+ class UNetModel(nn.Module):
397
+ """
398
+ The full UNet model with attention and timestep embedding.
399
+
400
+ :param in_channels: channels in the input Tensor.
401
+ :param model_channels: base channel count for the model.
402
+ :param out_channels: channels in the output Tensor.
403
+ :param num_res_blocks: number of residual blocks per downsample.
404
+ :param attention_resolutions: a collection of downsample rates at which
405
+ attention will take place. May be a set, list, or tuple.
406
+ For example, if this contains 4, then at 4x downsampling, attention
407
+ will be used.
408
+ :param dropout: the dropout probability.
409
+ :param channel_mult: channel multiplier for each level of the UNet.
410
+ :param conv_resample: if True, use learned convolutions for upsampling and
411
+ downsampling.
412
+ :param dims: determines if the signal is 1D, 2D, or 3D.
413
+ :param num_classes: if specified (as an int), then this model will be
414
+ class-conditional with `num_classes` classes.
415
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
416
+ :param num_heads: the number of attention heads in each attention layer.
417
+ :param num_heads_channels: if specified, ignore num_heads and instead use
418
+ a fixed channel width per attention head.
419
+ :param num_heads_upsample: works with num_heads to set a different number
420
+ of heads for upsampling. Deprecated.
421
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
422
+ :param resblock_updown: use residual blocks for up/downsampling.
423
+ :param use_new_attention_order: use a different attention pattern for potentially
424
+ increased efficiency.
425
+ """
426
+
427
+ def __init__(
428
+ self,
429
+ image_size,
430
+ in_channels,
431
+ model_channels,
432
+ out_channels,
433
+ num_res_blocks,
434
+ attention_resolutions,
435
+ dropout=0,
436
+ channel_mult=(1, 2, 4, 8),
437
+ conv_resample=True,
438
+ dims=2,
439
+ num_classes=None,
440
+ use_checkpoint=False,
441
+ use_fp16=False,
442
+ num_heads=1,
443
+ num_head_channels=-1,
444
+ num_heads_upsample=-1,
445
+ use_scale_shift_norm=False,
446
+ resblock_updown=False,
447
+ use_new_attention_order=False,
448
+ ):
449
+ super().__init__()
450
+
451
+ if num_heads_upsample == -1:
452
+ num_heads_upsample = num_heads
453
+
454
+ self.image_size = image_size
455
+ self.in_channels = in_channels
456
+ self.model_channels = model_channels
457
+ self.out_channels = out_channels
458
+ self.num_res_blocks = num_res_blocks
459
+ self.attention_resolutions = attention_resolutions
460
+ self.dropout = dropout
461
+ self.channel_mult = channel_mult
462
+ self.conv_resample = conv_resample
463
+ self.num_classes = num_classes
464
+ self.use_checkpoint = use_checkpoint
465
+ self.dtype = th.float16 if use_fp16 else th.float32
466
+ self.num_heads = num_heads
467
+ self.num_head_channels = num_head_channels
468
+ self.num_heads_upsample = num_heads_upsample
469
+
470
+ time_embed_dim = model_channels * 4
471
+ self.time_embed = nn.Sequential(
472
+ linear(model_channels, time_embed_dim),
473
+ nn.SiLU(),
474
+ linear(time_embed_dim, time_embed_dim),
475
+ )
476
+
477
+ if self.num_classes is not None:
478
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
479
+
480
+ ch = input_ch = int(channel_mult[0] * model_channels)
481
+ self.input_blocks = nn.ModuleList(
482
+ [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
483
+ )
484
+ self._feature_size = ch
485
+ input_block_chans = [ch]
486
+ ds = 1
487
+ for level, mult in enumerate(channel_mult):
488
+ for _ in range(num_res_blocks):
489
+ layers = [
490
+ ResBlock(
491
+ ch,
492
+ time_embed_dim,
493
+ dropout,
494
+ out_channels=int(mult * model_channels),
495
+ dims=dims,
496
+ use_checkpoint=use_checkpoint,
497
+ use_scale_shift_norm=use_scale_shift_norm,
498
+ )
499
+ ]
500
+ ch = int(mult * model_channels)
501
+ if ds in attention_resolutions:
502
+ layers.append(
503
+ AttentionBlock(
504
+ ch,
505
+ use_checkpoint=use_checkpoint,
506
+ num_heads=num_heads,
507
+ num_head_channels=num_head_channels,
508
+ use_new_attention_order=use_new_attention_order,
509
+ )
510
+ )
511
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
512
+ self._feature_size += ch
513
+ input_block_chans.append(ch)
514
+ if level != len(channel_mult) - 1:
515
+ out_ch = ch
516
+ self.input_blocks.append(
517
+ TimestepEmbedSequential(
518
+ ResBlock(
519
+ ch,
520
+ time_embed_dim,
521
+ dropout,
522
+ out_channels=out_ch,
523
+ dims=dims,
524
+ use_checkpoint=use_checkpoint,
525
+ use_scale_shift_norm=use_scale_shift_norm,
526
+ down=True,
527
+ )
528
+ if resblock_updown
529
+ else Downsample(
530
+ ch, conv_resample, dims=dims, out_channels=out_ch
531
+ )
532
+ )
533
+ )
534
+ ch = out_ch
535
+ input_block_chans.append(ch)
536
+ ds *= 2
537
+ self._feature_size += ch
538
+
539
+ self.middle_block = TimestepEmbedSequential(
540
+ ResBlock(
541
+ ch,
542
+ time_embed_dim,
543
+ dropout,
544
+ dims=dims,
545
+ use_checkpoint=use_checkpoint,
546
+ use_scale_shift_norm=use_scale_shift_norm,
547
+ ),
548
+ AttentionBlock(
549
+ ch,
550
+ use_checkpoint=use_checkpoint,
551
+ num_heads=num_heads,
552
+ num_head_channels=num_head_channels,
553
+ use_new_attention_order=use_new_attention_order,
554
+ ),
555
+ ResBlock(
556
+ ch,
557
+ time_embed_dim,
558
+ dropout,
559
+ dims=dims,
560
+ use_checkpoint=use_checkpoint,
561
+ use_scale_shift_norm=use_scale_shift_norm,
562
+ ),
563
+ )
564
+ self._feature_size += ch
565
+
566
+ self.output_blocks = nn.ModuleList([])
567
+ for level, mult in list(enumerate(channel_mult))[::-1]:
568
+ for i in range(num_res_blocks + 1):
569
+ ich = input_block_chans.pop()
570
+ layers = [
571
+ ResBlock(
572
+ ch + ich,
573
+ time_embed_dim,
574
+ dropout,
575
+ out_channels=int(model_channels * mult),
576
+ dims=dims,
577
+ use_checkpoint=use_checkpoint,
578
+ use_scale_shift_norm=use_scale_shift_norm,
579
+ )
580
+ ]
581
+ ch = int(model_channels * mult)
582
+ if ds in attention_resolutions:
583
+ layers.append(
584
+ AttentionBlock(
585
+ ch,
586
+ use_checkpoint=use_checkpoint,
587
+ num_heads=num_heads_upsample,
588
+ num_head_channels=num_head_channels,
589
+ use_new_attention_order=use_new_attention_order,
590
+ )
591
+ )
592
+ if level and i == num_res_blocks:
593
+ out_ch = ch
594
+ layers.append(
595
+ ResBlock(
596
+ ch,
597
+ time_embed_dim,
598
+ dropout,
599
+ out_channels=out_ch,
600
+ dims=dims,
601
+ use_checkpoint=use_checkpoint,
602
+ use_scale_shift_norm=use_scale_shift_norm,
603
+ up=True,
604
+ )
605
+ if resblock_updown
606
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
607
+ )
608
+ ds //= 2
609
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
610
+ self._feature_size += ch
611
+
612
+ self.out = nn.Sequential(
613
+ normalization(ch),
614
+ nn.SiLU(),
615
+ zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
616
+ )
617
+
618
+ def convert_to_fp16(self):
619
+ """
620
+ Convert the torso of the model to float16.
621
+ """
622
+ self.input_blocks.apply(convert_module_to_f16)
623
+ self.middle_block.apply(convert_module_to_f16)
624
+ self.output_blocks.apply(convert_module_to_f16)
625
+
626
+ def convert_to_fp32(self):
627
+ """
628
+ Convert the torso of the model to float32.
629
+ """
630
+ self.input_blocks.apply(convert_module_to_f32)
631
+ self.middle_block.apply(convert_module_to_f32)
632
+ self.output_blocks.apply(convert_module_to_f32)
633
+
634
+ def forward(self, x, timesteps, y=None):
635
+ """
636
+ Apply the model to an input batch.
637
+
638
+ :param x: an [N x C x ...] Tensor of inputs.
639
+ :param timesteps: a 1-D batch of timesteps.
640
+ :param y: an [N] Tensor of labels, if class-conditional.
641
+ :return: an [N x C x ...] Tensor of outputs.
642
+ """
643
+ # assert (y is not None) == (
644
+ # self.num_classes is not None
645
+ # ), "must specify y if and only if the model is class-conditional"
646
+
647
+ hs = []
648
+ emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
649
+
650
+ if self.num_classes is not None:
651
+ if y is None:
652
+ pass
653
+ else:
654
+ assert y.shape == (x.shape[0],)
655
+ emb = emb + self.label_emb(y)
656
+
657
+ h = x.type(self.dtype)
658
+ for module in self.input_blocks:
659
+ h = module(h, emb)
660
+ hs.append(h)
661
+ h = self.middle_block(h, emb)
662
+ for module in self.output_blocks:
663
+ h = th.cat([h, hs.pop()], dim=1)
664
+ h = module(h, emb)
665
+ h = h.type(x.dtype)
666
+ return self.out(h)
667
+
668
+
669
+ class SuperResModel(UNetModel):
670
+ """
671
+ A UNetModel that performs super-resolution.
672
+
673
+ Expects an extra kwarg `low_res` to condition on a low-resolution image.
674
+ """
675
+
676
+ def __init__(self, image_size, in_channels, *args, **kwargs):
677
+ super().__init__(image_size, in_channels * 2, *args, **kwargs)
678
+
679
+ def forward(self, x, timesteps, low_res=None, **kwargs):
680
+ _, _, new_height, new_width = x.shape
681
+ upsampled = F.interpolate(low_res, (new_height, new_width), mode="bilinear")
682
+ x = th.cat([x, upsampled], dim=1)
683
+ return super().forward(x, timesteps, **kwargs)
684
+
685
+
686
+ class EncoderUNetModel(nn.Module):
687
+ """
688
+ The half UNet model with attention and timestep embedding.
689
+
690
+ For usage, see UNet.
691
+ """
692
+
693
+ def __init__(
694
+ self,
695
+ image_size,
696
+ in_channels,
697
+ model_channels,
698
+ out_channels,
699
+ num_res_blocks,
700
+ attention_resolutions,
701
+ dropout=0,
702
+ channel_mult=(1, 2, 4, 8),
703
+ conv_resample=True,
704
+ dims=2,
705
+ use_checkpoint=False,
706
+ use_fp16=False,
707
+ num_heads=1,
708
+ num_head_channels=-1,
709
+ num_heads_upsample=-1,
710
+ use_scale_shift_norm=False,
711
+ resblock_updown=False,
712
+ use_new_attention_order=False,
713
+ pool="adaptive",
714
+ ):
715
+ super().__init__()
716
+
717
+ if num_heads_upsample == -1:
718
+ num_heads_upsample = num_heads
719
+
720
+ self.in_channels = in_channels
721
+ self.model_channels = model_channels
722
+ self.out_channels = out_channels
723
+ self.num_res_blocks = num_res_blocks
724
+ self.attention_resolutions = attention_resolutions
725
+ self.dropout = dropout
726
+ self.channel_mult = channel_mult
727
+ self.conv_resample = conv_resample
728
+ self.use_checkpoint = use_checkpoint
729
+ self.dtype = th.float16 if use_fp16 else th.float32
730
+ self.num_heads = num_heads
731
+ self.num_head_channels = num_head_channels
732
+ self.num_heads_upsample = num_heads_upsample
733
+
734
+ time_embed_dim = model_channels * 4
735
+ self.time_embed = nn.Sequential(
736
+ linear(model_channels, time_embed_dim),
737
+ nn.SiLU(),
738
+ linear(time_embed_dim, time_embed_dim),
739
+ )
740
+
741
+ ch = int(channel_mult[0] * model_channels)
742
+ self.input_blocks = nn.ModuleList(
743
+ [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
744
+ )
745
+ self._feature_size = ch
746
+ input_block_chans = [ch]
747
+ ds = 1
748
+ for level, mult in enumerate(channel_mult):
749
+ for _ in range(num_res_blocks):
750
+ layers = [
751
+ ResBlock(
752
+ ch,
753
+ time_embed_dim,
754
+ dropout,
755
+ out_channels=int(mult * model_channels),
756
+ dims=dims,
757
+ use_checkpoint=use_checkpoint,
758
+ use_scale_shift_norm=use_scale_shift_norm,
759
+ )
760
+ ]
761
+ ch = int(mult * model_channels)
762
+ if ds in attention_resolutions:
763
+ layers.append(
764
+ AttentionBlock(
765
+ ch,
766
+ use_checkpoint=use_checkpoint,
767
+ num_heads=num_heads,
768
+ num_head_channels=num_head_channels,
769
+ use_new_attention_order=use_new_attention_order,
770
+ )
771
+ )
772
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
773
+ self._feature_size += ch
774
+ input_block_chans.append(ch)
775
+ if level != len(channel_mult) - 1:
776
+ out_ch = ch
777
+ self.input_blocks.append(
778
+ TimestepEmbedSequential(
779
+ ResBlock(
780
+ ch,
781
+ time_embed_dim,
782
+ dropout,
783
+ out_channels=out_ch,
784
+ dims=dims,
785
+ use_checkpoint=use_checkpoint,
786
+ use_scale_shift_norm=use_scale_shift_norm,
787
+ down=True,
788
+ )
789
+ if resblock_updown
790
+ else Downsample(
791
+ ch, conv_resample, dims=dims, out_channels=out_ch
792
+ )
793
+ )
794
+ )
795
+ ch = out_ch
796
+ input_block_chans.append(ch)
797
+ ds *= 2
798
+ self._feature_size += ch
799
+
800
+ self.middle_block = TimestepEmbedSequential(
801
+ ResBlock(
802
+ ch,
803
+ time_embed_dim,
804
+ dropout,
805
+ dims=dims,
806
+ use_checkpoint=use_checkpoint,
807
+ use_scale_shift_norm=use_scale_shift_norm,
808
+ ),
809
+ AttentionBlock(
810
+ ch,
811
+ use_checkpoint=use_checkpoint,
812
+ num_heads=num_heads,
813
+ num_head_channels=num_head_channels,
814
+ use_new_attention_order=use_new_attention_order,
815
+ ),
816
+ ResBlock(
817
+ ch,
818
+ time_embed_dim,
819
+ dropout,
820
+ dims=dims,
821
+ use_checkpoint=use_checkpoint,
822
+ use_scale_shift_norm=use_scale_shift_norm,
823
+ ),
824
+ )
825
+ self._feature_size += ch
826
+ self.pool = pool
827
+ if pool == "adaptive":
828
+ self.out = nn.Sequential(
829
+ normalization(ch),
830
+ nn.SiLU(),
831
+ nn.AdaptiveAvgPool2d((1, 1)),
832
+ zero_module(conv_nd(dims, ch, out_channels, 1)),
833
+ nn.Flatten(),
834
+ )
835
+ elif pool == "attention":
836
+ assert num_head_channels != -1
837
+ self.out = nn.Sequential(
838
+ normalization(ch),
839
+ nn.SiLU(),
840
+ AttentionPool2d(
841
+ (image_size // ds), ch, num_head_channels, out_channels
842
+ ),
843
+ )
844
+ elif pool == "spatial":
845
+ self.out = nn.Sequential(
846
+ nn.Linear(self._feature_size, 2048),
847
+ nn.ReLU(),
848
+ nn.Linear(2048, self.out_channels),
849
+ )
850
+ elif pool == "spatial_v2":
851
+ self.out = nn.Sequential(
852
+ nn.Linear(self._feature_size, 2048),
853
+ normalization(2048),
854
+ nn.SiLU(),
855
+ nn.Linear(2048, self.out_channels),
856
+ )
857
+ else:
858
+ raise NotImplementedError(f"Unexpected {pool} pooling")
859
+
860
+ def convert_to_fp16(self):
861
+ """
862
+ Convert the torso of the model to float16.
863
+ """
864
+ self.input_blocks.apply(convert_module_to_f16)
865
+ self.middle_block.apply(convert_module_to_f16)
866
+
867
+ def convert_to_fp32(self):
868
+ """
869
+ Convert the torso of the model to float32.
870
+ """
871
+ self.input_blocks.apply(convert_module_to_f32)
872
+ self.middle_block.apply(convert_module_to_f32)
873
+
874
+ def forward(self, x, timesteps):
875
+ """
876
+ Apply the model to an input batch.
877
+
878
+ :param x: an [N x C x ...] Tensor of inputs.
879
+ :param timesteps: a 1-D batch of timesteps.
880
+ :return: an [N x K] Tensor of outputs.
881
+ """
882
+ emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
883
+
884
+ results = []
885
+ h = x.type(self.dtype)
886
+ for module in self.input_blocks:
887
+ h = module(h, emb)
888
+ if self.pool.startswith("spatial"):
889
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
890
+ h = self.middle_block(h, emb)
891
+ if self.pool.startswith("spatial"):
892
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
893
+ h = th.cat(results, axis=-1)
894
+ return self.out(h)
895
+ else:
896
+ h = h.type(x.dtype)
897
+ return self.out(h)
guided_diffusion/model-card.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Overview
2
+
3
+ These are diffusion models and noised image classifiers described in the paper [Diffusion Models Beat GANs on Image Synthesis](https://arxiv.org/abs/2105.05233).
4
+ Included in this release are the following models:
5
+
6
+ * Noisy ImageNet classifiers at resolutions 64x64, 128x128, 256x256, 512x512
7
+ * A class-unconditional ImageNet diffusion model at resolution 256x256
8
+ * Class conditional ImageNet diffusion models at 64x64, 128x128, 256x256, 512x512 resolutions
9
+ * Class-conditional ImageNet upsampling diffusion models: 64x64->256x256, 128x128->512x512
10
+ * Diffusion models trained on three LSUN classes at 256x256 resolution: cat, horse, bedroom
11
+
12
+ # Datasets
13
+
14
+ All of the models we are releasing were either trained on the [ILSVRC 2012 subset of ImageNet](http://www.image-net.org/challenges/LSVRC/2012/) or on single classes of [LSUN](https://arxiv.org/abs/1506.03365).
15
+ Here, we describe characteristics of these datasets which impact model behavior:
16
+
17
+ **LSUN**: This dataset was collected in 2015 using a combination of human labeling (from Amazon Mechanical Turk) and automated data labeling.
18
+ * Each of the three classes we consider contain over a million images.
19
+ * The dataset creators found that the label accuracy was roughly 90% across the entire LSUN dataset when measured by trained experts.
20
+ * Images are scraped from the internet, and LSUN cat images in particular tend to often follow a “meme” format.
21
+ * We found that there are occasionally humans in these photos, including faces, especially within the cat class.
22
+
23
+ **ILSVRC 2012 subset of ImageNet**: This dataset was curated in 2012 and consists of roughly one million images, each belonging to one of 1000 classes.
24
+ * A large portion of the classes in this dataset are animals, plants, and other naturally-occurring objects.
25
+ * Many images contain humans, although usually these humans aren’t reflected by the class label (e.g. the class “Tench, tinca tinca” contains many photos of people holding fish).
26
+
27
+ # Performance
28
+
29
+ These models are intended to generate samples consistent with their training distributions.
30
+ This has been measured in terms of FID, Precision, and Recall.
31
+ These metrics all rely on the representations of a [pre-trained Inception-V3 model](https://arxiv.org/abs/1512.00567),
32
+ which was trained on ImageNet, and so is likely to focus more on the ImageNet classes (such as animals) than on other visual features (such as human faces).
33
+
34
+ Qualitatively, the samples produced by these models often look highly realistic, especially when a diffusion model is combined with a noisy classifier.
35
+
36
+ # Intended Use
37
+
38
+ These models are intended to be used for research purposes only.
39
+ In particular, they can be used as a baseline for generative modeling research, or as a starting point to build off of for such research.
40
+
41
+ These models are not intended to be commercially deployed.
42
+ Additionally, they are not intended to be used to create propaganda or offensive imagery.
43
+
44
+ Before releasing these models, we probed their ability to ease the creation of targeted imagery, since doing so could be potentially harmful.
45
+ We did this either by fine-tuning our ImageNet models on a target LSUN class, or through classifier guidance with publicly available [CLIP models](https://github.com/openai/CLIP).
46
+ * To probe fine-tuning capabilities, we restricted our compute budget to roughly $100 and tried both standard fine-tuning,
47
+ and a diffusion-specific approach where we train a specialized classifier for the LSUN class. The resulting FIDs were significantly worse than publicly available GAN models, indicating that fine-tuning an ImageNet diffusion model does not significantly lower the cost of image generation.
48
+ * To probe guidance with CLIP, we tried two approaches for using pre-trained CLIP models for classifier guidance. Either we fed the noised image to CLIP directly and used its gradients, or we fed the diffusion model's denoised prediction to the CLIP model and differentiated through the whole process. In both cases, we found that it was difficult to recover information from the CLIP model, indicating that these diffusion models are unlikely to make it significantly easier to extract knowledge from CLIP compared to existing GAN models.
49
+
50
+ # Limitations
51
+
52
+ These models sometimes produce highly unrealistic outputs, particularly when generating images containing human faces.
53
+ This may stem from ImageNet's emphasis on non-human objects.
54
+
55
+ While classifier guidance can improve sample quality, it reduces diversity, resulting in some modes of the data distribution being underrepresented.
56
+ This can potentially amplify existing biases in the training dataset such as gender and racial biases.
57
+
58
+ Because ImageNet and LSUN contain images from the internet, they include photos of real people, and the model may have memorized some of the information contained in these photos.
59
+ However, these images are already publicly available, and existing generative models trained on ImageNet have not demonstrated significant leakage of this information.
guided_diffusion/setup.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from setuptools import setup
2
+
3
+ setup(
4
+ name="guided-diffusion",
5
+ py_modules=["guided_diffusion"],
6
+ install_requires=["blobfile>=1.0.5", "torch", "tqdm"],
7
+ )
networks/distill_model.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torchvision.models as TVM
3
+ from collections import OrderedDict
4
+ from guided_diffusion.guided_diffusion.fp16_util import convert_module_to_f16
5
+
6
+ import torch
7
+
8
+ # ------------------------------------------------------------------------------
9
+ # Model Definition
10
+ class DistilDIRE(torch.nn.Module):
11
+ def __init__(self, device):
12
+ super(DistilDIRE, self).__init__()
13
+
14
+ # define models
15
+ student = TVM.resnet50()
16
+ self.student_backbone = nn.Sequential(OrderedDict([*(list(student.named_children())[:-2])])) # drop last layer which is classifier
17
+ # extract last classifier head from teacher resnet
18
+ self.student_head = nn.Sequential(nn.AdaptiveAvgPool2d(1),
19
+ nn.Flatten(),
20
+ nn.Linear(2048, 1))
21
+ self.student_backbone.conv1 = nn.Conv2d(6, 64, kernel_size=7, stride=2, padding=3, bias=False)
22
+ self.device = device
23
+
24
+ def convert_to_fp16_student(self):
25
+ self.student_backbone.apply(convert_module_to_f16)
26
+
27
+
28
+ def forward(self, img, eps):
29
+ img = img.to(self.device)
30
+ eps = eps.to(self.device)
31
+
32
+ # concat image and noise
33
+ img_tens = torch.cat([img, eps], dim=1)
34
+
35
+ feature = self.student_backbone(img_tens)
36
+ logit = self.student_head(feature)
37
+ return {'logit':logit, 'feature':feature}
38
+
39
+
40
+ # ------------------------------------------------------------------------------
41
+ class DistilDIREOnlyEPS(DistilDIRE):
42
+ def __init__(self, device):
43
+ super(DistilDIREOnlyEPS, self).__init__(device)
44
+ self.student_backbone.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
45
+ self.student_head = nn.Sequential(nn.AdaptiveAvgPool2d(1),
46
+ nn.Flatten(),
47
+ nn.Linear(2048, 1))
48
+
49
+ def forward(self, eps):
50
+ eps = eps.to(self.device)
51
+ feature = self.student_backbone(eps)
52
+ logit = self.student_head(feature)
53
+ return {'logit':logit, 'feature':feature}
54
+
55
+
56
+ # ------------------------------------------------------------------------------
57
+ class DIRE(torch.nn.Module):
58
+ def __init__(self, device):
59
+ super(DIRE, self).__init__()
60
+
61
+ # define models
62
+ student = TVM.resnet50()
63
+ self.student_backbone = nn.Sequential(OrderedDict([*(list(student.named_children())[:-2])])) # drop last layer which is classifier
64
+ # extract last classifier head from teacher resnet
65
+ self.student_head = nn.Sequential(nn.AdaptiveAvgPool2d(1),
66
+ nn.Flatten(),
67
+ nn.Linear(2048, 1))
68
+ self.device = device
69
+
70
+
71
+ def forward(self, dire):
72
+ dire = dire.to(self.device)
73
+
74
+ feature = self.student_backbone(dire)
75
+ logit = self.student_head(feature)
76
+ return {'logit':logit, 'feature':feature}
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # conda create -n dire python=3.9
2
+ # pip install torch==2.0.0+cu117 torchvision==0.15.1+cu117 -f https://download.pytorch.org/whl/torch_stable.html
3
+ einops
4
+ imageio
5
+ ipympl
6
+ cmake==3.28.3
7
+ dlib==19.24.2
8
+ decord
9
+ face_recognition
10
+ matplotlib
11
+ numpy
12
+ opencv-python==4.9.0.80
13
+ pandas
14
+ scikit-learn
15
+ tensorboard
16
+ tensorboardX
17
+ sanic
18
+ wandb
19
+ tqdm
20
+ blobfile>=1.0.5
21
+ easydict
server.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Two server routes that OctoAI containers should have:
2
+ # a route for inference requests (e.g. ”/predict”). This route for inference requests must receive JSON inputs and JSON outputs.
3
+ # a route for health checks (e.g. ”/healthcheck”).
4
+ # Number of workers (not required). Typical best practice is to make this number some function of the # of CPU cores that the server has access to and should use.
5
+
6
+ """HTTP Inference serving interface using sanic."""
7
+ import os
8
+
9
+ from custommodel import CustomModel
10
+ from sanic import Request, Sanic, response
11
+
12
+ _DEFAULT_PORT = 8000
13
+ """Default port to serve inference on."""
14
+
15
+ # Load and initialize the model on startup globally, so it can be reused.
16
+ model_instance = CustomModel(ckpt='models/distil-240709-tot-model_epoch_20.pth')
17
+ """Global instance of the model to serve."""
18
+
19
+ server = Sanic("server")
20
+ """Global instance of the web server."""
21
+
22
+
23
+ @server.route("/healthcheck", methods=["GET"])
24
+ def healthcheck(_: Request) -> response.JSONResponse:
25
+ """Responds to healthcheck requests.
26
+
27
+ :param request: the incoming healthcheck request.
28
+ :return: json responding to the healthcheck.
29
+ """
30
+ return response.json({"healthy": "yes"})
31
+
32
+
33
+ @server.route("/reconstruction/predict", methods=["POST"])
34
+ def predict(request: Request) -> response.JSONResponse:
35
+ """Responds to inference/prediction requests.
36
+
37
+ :param request: the incoming request containing inputs for the model.
38
+ :return: json containing the inference results.
39
+ """
40
+
41
+ try:
42
+ inputs = request.json
43
+ output = model_instance.predict(inputs)
44
+ return response.json(output)
45
+ except Exception as e:
46
+ return response.json({'error': str(e)}, status=500)
47
+
48
+
49
+ def main():
50
+ """Entry point for the server."""
51
+ port = int(os.environ.get("SERVING_PORT", _DEFAULT_PORT))
52
+ server.run(host="0.0.0.0", port=port, workers=1)
53
+
54
+ if __name__ == "__main__":
55
+ main()
test.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import wandb
2
+ from utils.config import cfg
3
+
4
+
5
+ def main(run, cfg):
6
+ from utils.trainer import Trainer
7
+ from torch.utils.data import DataLoader
8
+ from dataset import TMEPSOnlyDataset, TMIMGOnlyDataset
9
+ print(cfg.dataset_test_root)
10
+ # dataset =TMEPSOnlyDataset(cfg.dataset_test_root, False)
11
+ dataset = TMIMGOnlyDataset(cfg.dataset_test_root, istrain=False)
12
+ dataloader = DataLoader(dataset,
13
+ batch_size=1,
14
+ shuffle=True, num_workers=2)
15
+ trainer = Trainer(cfg, dataloader, dataloader, run, 0, False, 1)
16
+ assert len(cfg.pretrained_weights) != 0, "Give proper checkpoint path"
17
+ trainer.load_networks(cfg.pretrained_weights)
18
+ trainer.validate(False, save=True, save_name=f"{cfg.root_dir}/{cfg.datasets_test}_{cfg.pretrained_weights.split('/')[-1]}_results.txt")
19
+
20
+ if __name__ == "__main__":
21
+ main(None, cfg)
22
+
train.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import torch
4
+
5
+
6
+ def main(run, cfg):
7
+ from torch.utils.data.distributed import DistributedSampler
8
+ from utils.trainer import Trainer
9
+
10
+ if cfg.reproduce_dire:
11
+ dataset = TMDireDataset(cfg.dataset_root)
12
+ val_dataset = TMDireDataset(cfg.dataset_test_root)
13
+ elif cfg.only_eps:
14
+ dataset = TMEPSOnlyDataset(cfg.dataset_root)
15
+ val_dataset = TMEPSOnlyDataset(cfg.dataset_root)
16
+
17
+ elif cfg.only_img:
18
+ dataset = TMIMGOnlyDataset(cfg.dataset_root, istrain=True)
19
+ val_dataset = TMIMGOnlyDataset(cfg.dataset_test_root, istrain=False)
20
+ else:
21
+ dataset= TMDistilDireDataset(cfg.dataset_root)
22
+ val_dataset = TMDistilDireDataset(cfg.dataset_test_root)
23
+ sampler = DistributedSampler(dataset)
24
+ val_samlper = DistributedSampler(val_dataset)
25
+ dataloader = DataLoader(dataset,
26
+ batch_size=cfg.batch_size,
27
+ sampler=sampler,
28
+ num_workers=2)
29
+ val_loader = DataLoader(val_dataset,
30
+ batch_size=cfg.batch_size,
31
+ sampler=val_samlper,
32
+ num_workers=2)
33
+ trainer = Trainer(cfg, dataloader, val_loader, run, local_rank, True, world_size, cfg.kd)
34
+ if cfg.pretrained_weights:
35
+ trainer.load_networks(cfg.pretrained_weights)
36
+ trainer.train()
37
+
38
+
39
+ if __name__ == "__main__":
40
+
41
+ import torch.distributed as dist
42
+ import os
43
+ import wandb
44
+
45
+ from torch.utils.data import DataLoader
46
+ from dataset import TMDistilDireDataset, TMDireDataset, TMEPSOnlyDataset, TMIMGOnlyDataset
47
+
48
+ dist.init_process_group(backend='nccl', init_method='env://')
49
+ local_rank = int(os.environ['LOCAL_RANK'])
50
+ world_size = int(os.environ['WORLD_SIZE'])
51
+ torch.cuda.set_device(local_rank)
52
+ dist.barrier()
53
+ from utils.config import cfg
54
+ run = None
55
+ if local_rank == 0:
56
+ run = wandb.init(project=f'dire-distill-truemedia', config=cfg, dir=cfg.exp_dir)
57
+ main(run, cfg)
58
+
59
+
train.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #! /bin/bash
2
+
3
+ torchrun --standalone --nproc_per_node 1 -m train --batch 64 --exp_name 240709-tot-finetune-from-scratch-fp16-distildire-w-prp-pos2 --datasets truemedia-total --datasets_test truemedia-external --epoch 50 --lr 1e-4 --pretrained_weights /home/ubuntu/y1/DistilDIRE/experiments/240709-tot-finetune-from-scratch-fp16-distildire-w-prp/ckpt/model_epoch_4.pth
utils/config.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+ from abc import ABC
5
+ from typing import Type
6
+
7
+
8
+ class DefaultConfigs(ABC):
9
+ ####### base setting ######
10
+ gpus = [0]
11
+ seed = 3407
12
+ arch = "resnet50"
13
+ datasets = [""]
14
+ datasets_test = [""]
15
+ class_bal = False
16
+ batch_size = 256
17
+ val_every = 1
18
+ loadSize = 256
19
+ cropSize = 224
20
+ epoch = "latest"
21
+ num_workers = 2
22
+ isTrain = True
23
+
24
+ ####### train setting ######
25
+ warmup = False
26
+ warmup_epoch = 3
27
+ earlystop = True
28
+ earlystop_epoch = 5
29
+ optim = "adam"
30
+ new_optim = False
31
+ loss_freq = 400
32
+ save_latest_freq = 2000
33
+ save_epoch_freq = 20
34
+ continue_train = False
35
+ epoch_count = 1
36
+ last_epoch = -1
37
+ nepoch = 20
38
+ beta1 = 0.9
39
+ lr = 0.00001
40
+ init_type = "normal"
41
+ init_gain = 0.02
42
+ pretrained = True
43
+
44
+ # paths information
45
+ root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
46
+ dataset_root = os.path.join(root_dir, "datasets")
47
+ dataset_test_root = os.path.join(root_dir, "datasets")
48
+ exp_root = os.path.join(root_dir, "experiments")
49
+ _exp_name = ""
50
+ exp_dir = ""
51
+ ckpt_dir = ""
52
+ logs_path = ""
53
+ ckpt_path = ""
54
+ pretrained_weights = ""
55
+ kd = True
56
+ kd_weight = 1.
57
+ reproduce_dire = False
58
+ only_eps = False
59
+ only_img = False
60
+
61
+ @property
62
+ def exp_name(self):
63
+ return self._exp_name
64
+
65
+ @exp_name.setter
66
+ def exp_name(self, value: str):
67
+ self._exp_name = value
68
+ self.exp_dir: str = os.path.join(self.exp_root, self.exp_name)
69
+ self.ckpt_dir: str = os.path.join(self.exp_dir, "ckpt")
70
+ self.logs_path: str = os.path.join(self.exp_dir, "logs.txt")
71
+ if self.isTrain:
72
+ os.makedirs(self.exp_dir, exist_ok=True)
73
+ os.makedirs(self.ckpt_dir, exist_ok=True)
74
+
75
+ def to_dict(self):
76
+ dic = {}
77
+ for fieldkey in dir(self):
78
+ fieldvalue = getattr(self, fieldkey)
79
+ if not fieldkey.startswith("__") and not callable(fieldvalue) and not fieldkey.startswith("_"):
80
+ dic[fieldkey] = fieldvalue
81
+ return dic
82
+
83
+
84
+ def args_list2dict(arg_list: list):
85
+ assert len(arg_list) % 2 == 0, f"Override list has odd length: {arg_list}; it must be a list of pairs"
86
+ return dict(zip(arg_list[::2], arg_list[1::2]))
87
+
88
+
89
+ def str2bool(v: str) -> bool:
90
+ if isinstance(v, bool):
91
+ return v
92
+ elif v.lower() in ("true", "yes", "on", "y", "t", "1"):
93
+ return True
94
+ elif v.lower() in ("false", "no", "off", "n", "f", "0"):
95
+ return False
96
+ else:
97
+ return bool(v)
98
+
99
+
100
+ def str2list(v: str, element_type=None) -> list:
101
+ if not isinstance(v, (list, tuple, set)):
102
+ v = v.lstrip("[").rstrip("]")
103
+ v = v.split(",")
104
+ v = list(map(str.strip, v))
105
+ if element_type is not None:
106
+ v = list(map(element_type, v))
107
+ return v
108
+
109
+
110
+ CONFIGCLASS = Type[DefaultConfigs]
111
+
112
+ parser = argparse.ArgumentParser()
113
+ parser.add_argument("--gpus", default="0", type=str)
114
+ parser.add_argument("--batch", default=256, type=int)
115
+ parser.add_argument("--epoch", default="100", type=int)
116
+ parser.add_argument("--exp_name", default="", type=str)
117
+ parser.add_argument("--datasets", default="", type=str)
118
+ parser.add_argument("--dataset_root", default="", type=str)
119
+ parser.add_argument("--datasets_test", default="", type=str)
120
+ parser.add_argument("--dataset_test_root", default="", type=str)
121
+ parser.add_argument("--pretrained_weights", default="", type=str)
122
+ parser.add_argument("--lr", default=0.00001, type=float)
123
+ parser.add_argument("--kd_weight", default=1., type=float)
124
+ parser.add_argument("--test", default=False, type=str2bool)
125
+ parser.add_argument("--reproduce_dire", default=False, type=str2bool)
126
+ parser.add_argument("--only_eps", default=False, type=str2bool)
127
+ parser.add_argument("--only_img", default=False, type=str2bool)
128
+ parser.add_argument("--kd", default=True, type=str2bool)
129
+ parser.add_argument("opts", default=[], nargs=argparse.REMAINDER)
130
+ args = parser.parse_args()
131
+
132
+ if os.path.exists(os.path.join(DefaultConfigs.exp_root, args.exp_name, "config.py")):
133
+ sys.path.insert(0, os.path.join(DefaultConfigs.exp_root, args.exp_name))
134
+ from config import cfg
135
+
136
+ cfg: CONFIGCLASS
137
+ else:
138
+ cfg = DefaultConfigs()
139
+
140
+ if args.opts:
141
+ opts = args_list2dict(args.opts)
142
+ for k, v in opts.items():
143
+ if not hasattr(cfg, k):
144
+ raise ValueError(f"Unrecognized option: {k}")
145
+ original_type = type(getattr(cfg, k))
146
+ if original_type == bool:
147
+ setattr(cfg, k, str2bool(v))
148
+ elif original_type in (list, tuple, set):
149
+ setattr(cfg, k, str2list(v, type(getattr(cfg, k)[0])))
150
+ else:
151
+ setattr(cfg, k, original_type(v))
152
+
153
+ #cfg.gpus: list = args.gpus
154
+ os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus#", ".join([str(gpu) for gpu in cfg.gpus])
155
+ if args.test:
156
+ cfg.isTrain = False
157
+ cfg.exp_name = args.exp_name
158
+ cfg.batch_size = args.batch
159
+ cfg.datasets = args.datasets
160
+ cfg.datasets_test = args.datasets_test if args.datasets_test else args.datasets
161
+ cfg.pretrained_weights = args.pretrained_weights
162
+ cfg.lr = args.lr
163
+ cfg.nepoch = args.epoch
164
+
165
+ root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
166
+ cfg.dataset_root = os.path.join(root_dir, 'datasets', cfg.datasets)
167
+ if args.dataset_root != "":
168
+ cfg.dataset_root = args.dataset_root
169
+ cfg.dataset_test_root = os.path.join(root_dir, 'datasets', cfg.datasets_test)
170
+ if args.dataset_test_root != "":
171
+ cfg.dataset_test_root = args.dataset_test_root
172
+ cfg.kd = args.kd
173
+ cfg.reproduce_dire = args.reproduce_dire
174
+ cfg.only_eps = args.only_eps
175
+ cfg.only_img = args.only_img
176
+ cfg.kd_weight = args.kd_weight
177
+
178
+ # if isinstance(cfg.datasets, str):
179
+ # cfg.datasets = cfg.datasets.split(",")
utils/sanic_utils.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from decord import VideoReader,cpu
2
+ import os
3
+ import numpy as np
4
+ import cv2
5
+ import dlib
6
+ import face_recognition
7
+ from tqdm import tqdm
8
+
9
+ def real_or_fake(prediction):
10
+ return {0: "REAL", 1: "FAKE"}[prediction ^ 1]
11
+
12
+
13
+ def real_or_fake_thres(probability, threshold=0.2):
14
+ return "FAKE" if probability >= threshold else "REAL"
15
+
16
+
17
+ def face_rec(frames, p=None, klass=None):
18
+ temp_face = np.zeros((len(frames), 224, 224, 3), dtype=np.uint8)
19
+ count = 0
20
+ mod = "cnn" if dlib.DLIB_USE_CUDA else "hog"
21
+
22
+ for _, frame in tqdm(enumerate(frames), total=len(frames)):
23
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
24
+ face_locations = face_recognition.face_locations(
25
+ frame, number_of_times_to_upsample=0, model=mod
26
+ )
27
+
28
+ for face_location in face_locations:
29
+ if count < len(frames):
30
+ top, right, bottom, left = face_location
31
+ face_image = frame[top:bottom, left:right]
32
+ face_image = cv2.resize(
33
+ face_image, (224, 224), interpolation=cv2.INTER_AREA
34
+ )
35
+ face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB)
36
+
37
+ temp_face[count] = face_image
38
+ count += 1
39
+ else:
40
+ break
41
+
42
+ return ([], 0) if count == 0 else (temp_face[:count], count)
43
+
44
+
45
+ def extract_frames(video_file, frames_nums=15):
46
+ vr = VideoReader(video_file, ctx=cpu(0))
47
+ # Calculate the step size between frames
48
+ step_size = max(1, len(vr) // frames_nums)
49
+ return vr.get_batch(
50
+ list(range(0, len(vr), step_size))[:frames_nums]
51
+ ).asnumpy() # seek frames with step_size
52
+
53
+ def is_video(vid):
54
+ return os.path.isfile(vid) and vid.endswith(
55
+ tuple([".avi", ".mp4", ".mpg", ".mpeg", ".mov"])
56
+ )
57
+
58
+ def is_image(img):
59
+ return os.path.isfile(img) and img.endswith(
60
+ tuple([".jpg", ".jpeg", ".png", ".webp"])
61
+ )
62
+
63
+ def set_result():
64
+ return {
65
+ "video": {
66
+ "name": [],
67
+ "pred": [],
68
+ "klass": [],
69
+ "pred_label": [],
70
+ "correct_label": [],
71
+ }
72
+ }
73
+
74
+ def store_result(
75
+ result, filename, y, y_val, klass, correct_label=None, compression=None
76
+ ):
77
+ result["video"]["name"].append(filename)
78
+ result["video"]["pred"].append(y_val)
79
+ result["video"]["klass"].append(klass.lower())
80
+ result["video"]["pred_label"].append(real_or_fake(y))
81
+
82
+ if correct_label is not None:
83
+ result["video"]["correct_label"].append(correct_label)
84
+
85
+ if compression is not None:
86
+ result["video"]["compression"].append(compression)
87
+
88
+ return result
utils/trainer.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+ import torchvision.models as TVM
6
+ from collections import OrderedDict
7
+ from sklearn.metrics import accuracy_score, average_precision_score, precision_score
8
+ from torchvision.io import decode_jpeg, encode_jpeg
9
+ import torch.distributed as dist
10
+ from tqdm.auto import tqdm
11
+ import numpy as np
12
+
13
+ from utils.config import CONFIGCLASS
14
+ from networks.distill_model import DistilDIRE, DIRE, DistilDIREOnlyEPS
15
+ from utils.warmup import GradualWarmupScheduler
16
+ import os.path as osp
17
+ from guided_diffusion.compute_dire_eps import dire_get_first_step_noise, create_dicts_for_static_init
18
+ from guided_diffusion.guided_diffusion.script_util import (
19
+ model_and_diffusion_defaults,
20
+ create_model_and_diffusion,
21
+ add_dict_to_argparser,
22
+ dict_parse,
23
+ args_to_dict,
24
+ )
25
+
26
+ class BaseModel(nn.Module):
27
+ def __init__(self, cfg: CONFIGCLASS):
28
+ super().__init__()
29
+ self.cfg = cfg
30
+ self.total_steps = 0
31
+ self.isTrain = cfg.isTrain
32
+ self.save_dir = cfg.ckpt_dir
33
+ self.nepoch = cfg.nepoch
34
+ self.device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
35
+ self.student: nn.Module
36
+ self.optimizer: torch.optim.Optimizer
37
+
38
+ def save_networks(self, epoch: int):
39
+ save_filename = f"model_epoch_{epoch}.pth"
40
+ save_path = os.path.join(self.save_dir, save_filename)
41
+
42
+ # serialize model and optimizer to dict
43
+ state_dict = {
44
+ "model": self.student.state_dict(),
45
+ "optimizer": self.optimizer.state_dict(),
46
+ "total_steps": self.total_steps,
47
+ }
48
+
49
+ torch.save(state_dict, save_path)
50
+
51
+ # load models from the disk
52
+ def load_networks(self, epoch: int):
53
+ load_filename = f"model_epoch_{epoch}.pth"
54
+ load_path = os.path.join(self.save_dir, load_filename)
55
+
56
+ print(f"loading the model from {load_path}")
57
+ # if you are using PyTorch newer than 0.4 (e.g., built from
58
+ # GitHub source), you can remove str() on self.device
59
+ state_dict = torch.load(load_path, map_location=self.device)["model"]
60
+ state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()}
61
+ if hasattr(state_dict, "_metadata"):
62
+ del state_dict._metadata
63
+
64
+ self.student.load_state_dict(state_dict)
65
+ self.total_steps = state_dict["total_steps"]
66
+
67
+ if self.isTrain and not self.cfg.new_optim:
68
+ self.optimizer.load_state_dict(state_dict["optimizer"])
69
+ # move optimizer state to GPU
70
+ for state in self.optimizer.state.values():
71
+ for k, v in state.items():
72
+ if torch.is_tensor(v):
73
+ state[k] = v.to(self.device)
74
+
75
+ for g in self.optimizer.param_groups:
76
+ g["lr"] = self.cfg.lr
77
+
78
+ def eval(self):
79
+ self.student.eval()
80
+
81
+ def test(self):
82
+ with torch.no_grad():
83
+ self.forward()
84
+
85
+
86
+ class Trainer(BaseModel):
87
+ def name(self):
88
+ return "DistilDIRE Trainer"
89
+
90
+ def __init__(self, cfg: CONFIGCLASS, train_loader, val_loader, run, rank=0, distributed=True, world_size=1, kd=True):
91
+ super().__init__(cfg)
92
+ self.arch = cfg.arch
93
+ self.reproduce_dire = cfg.reproduce_dire
94
+ self.only_eps = cfg.only_eps
95
+ self.only_img = cfg.only_img
96
+ self.test_name = osp.basename(cfg.dataset_test_root)
97
+ self.rank = rank
98
+ self.device = torch.device(f"cuda")
99
+ self.distributed = distributed
100
+ self.world_size = world_size
101
+ self.kd = kd
102
+ self.kd_weight = cfg.kd_weight
103
+
104
+ self.train_loader = train_loader
105
+ self.val_loader = val_loader
106
+
107
+ self.val_every = cfg.val_every
108
+ self.cur_epoch = 0
109
+
110
+ # wandb logger (pass if None)
111
+ self.run = run
112
+ self.adm = None
113
+ if self.reproduce_dire:
114
+ self.student = DIRE(self.device).to(self.device)
115
+ else:
116
+ if self.only_eps or self.only_img:
117
+ self.student = DistilDIREOnlyEPS(self.device).to(self.device)
118
+ if self.only_img:
119
+ adm_args = create_dicts_for_static_init()
120
+ adm_args['timestep_respacing'] = 'ddim20'
121
+ adm_model, diffusion = create_model_and_diffusion(**dict_parse(adm_args, model_and_diffusion_defaults().keys()))
122
+ adm_model.load_state_dict(torch.load(adm_args['model_path'], map_location="cpu"))
123
+ print("ADM model loaded...")
124
+ self.adm = adm_model
125
+ self.adm.convert_to_fp16()
126
+ self.adm.to(self.device)
127
+ self.adm.eval()
128
+ self.diffusion = diffusion
129
+ self.adm_args = adm_args
130
+ else:
131
+ self.student = DistilDIRE(self.device).to(self.device)
132
+ # self.student.convert_to_fp16_student()
133
+ __backbone = TVM.resnet50(weights=TVM.ResNet50_Weights.DEFAULT)
134
+ self.teacher = nn.Sequential(OrderedDict([*(list(__backbone.named_children())[:-2])])) # drop last layer which is classifier
135
+ self.teacher.eval().to(self.device)
136
+ # Freeze teacher model
137
+ for param in self.teacher.parameters():
138
+ param.requires_grad = False
139
+ self.kd_criterion = nn.MSELoss(reduction='mean')
140
+
141
+ self.cls_criterion = nn.BCEWithLogitsLoss(reduction='mean', pos_weight=torch.tensor(0.3))
142
+
143
+ # initialize optimizers
144
+ if cfg.optim == "adam":
145
+ self.optimizer = torch.optim.Adam(self.student.parameters(), lr=cfg.lr, betas=(cfg.beta1, 0.999))
146
+ elif cfg.optim == "sgd":
147
+ self.optimizer = torch.optim.SGD(self.student.parameters(), lr=cfg.lr, momentum=0.9, weight_decay=5e-4)
148
+ else:
149
+ raise ValueError("optim should be [adam, sgd]")
150
+
151
+ if self.distributed:
152
+ from torch.nn.parallel import DistributedDataParallel as DDP
153
+
154
+ self.student = DDP(self.student, device_ids=[rank], output_device=rank)
155
+
156
+ if cfg.warmup:
157
+ scheduler_cosine = torch.optim.lr_scheduler.CosineAnnealingLR(
158
+ self.optimizer, cfg.nepoch - cfg.warmup_epoch, eta_min=1e-6
159
+ )
160
+ self.scheduler = GradualWarmupScheduler(
161
+ self.optimizer, multiplier=1, total_epoch=cfg.warmup_epoch, after_scheduler=scheduler_cosine
162
+ )
163
+ self.scheduler.step()
164
+
165
+ def adjust_learning_rate(self, min_lr=1e-6):
166
+ for param_group in self.optimizer.param_groups:
167
+ param_group["lr"] /= 10.0
168
+ if param_group["lr"] < min_lr:
169
+ return False
170
+ return True
171
+
172
+
173
+ def set_input(self, input, istrain=True):
174
+ if self.reproduce_dire:
175
+ dire, label = input
176
+ self.dire = dire.to(self.device)
177
+ self.label = label.to(self.device).float()
178
+
179
+ else:
180
+ img, dire, eps, label = input # if len(input) == 3 else (input[0], input[1], {})
181
+ H, W = img.shape[-2:]
182
+ B = img.shape[0]
183
+
184
+ # random jpeg compression
185
+ if istrain:
186
+ comp_quality = torch.randint(10, 100, (B,))
187
+ img = (img+1)/2
188
+ img = (img*255).to(torch.uint8)
189
+ img = torch.stack([decode_jpeg(encode_jpeg(img[i], quality=int(comp_quality[i]))) for i in range(B)], dim=0)
190
+ img = img / 255.
191
+ img = (img*2)-1
192
+ # only-img
193
+ if self.only_img:
194
+ img = img.to(self.device)
195
+ # calc eps from img
196
+ eps = dire_get_first_step_noise(img, self.adm, self.diffusion, self.adm_args, self.device)
197
+
198
+ # cutmix
199
+ # if torch.rand(1) < 0.3 and istrain:
200
+ # c_lambda = torch.rand(1)
201
+ # r_x = torch.randint(0, W, (1,))
202
+ # r_y = torch.randint(0, H, (1,))
203
+ # r_w = int(torch.sqrt(1-c_lambda)*W)
204
+ # r_h = int(torch.sqrt(1-c_lambda)*H)
205
+
206
+ # img[:, :, r_y:r_y+r_h, r_x:r_x+r_w] = img[0:1, :, r_y:r_y+r_h, r_x:r_x+r_w].repeat(B, 1, 1, 1)
207
+ # dire[:, :, r_y:r_y+r_h, r_x:r_x+r_w] = dire[0:1, :, r_y:r_y+r_h, r_x:r_x+r_w].repeat(B, 1, 1, 1)
208
+ # eps[:, :, r_y:r_y+r_h, r_x:r_x+r_w] = eps[0:1, :, r_y:r_y+r_h, r_x:r_x+r_w].repeat(B, 1, 1, 1)
209
+ # label = c_lambda * label + (1-c_lambda) * label[0:1]
210
+ self.input = img.to(self.device)
211
+ self.dire = dire.to(self.device)
212
+ self.eps = eps.to(self.device)
213
+ self.label = label.to(self.device).float()
214
+
215
+
216
+ def forward(self):
217
+ if self.reproduce_dire:
218
+ self.output = self.student(self.dire)
219
+ else:
220
+ if self.only_eps or self.only_img:
221
+ self.output = self.student(self.eps)
222
+ else:
223
+ self.output = self.student(self.input, self.eps)
224
+ with torch.no_grad():
225
+ self.teacher_feature = self.teacher(self.dire)
226
+
227
+
228
+ def get_loss(self, kd=True):
229
+ loss = self.cls_criterion(self.output['logit'].squeeze(), self.label)
230
+ if kd and (not self.reproduce_dire):
231
+ loss2 = self.kd_criterion(self.output['feature'], self.teacher_feature)
232
+ loss = loss + loss2 * self.kd_weight
233
+ return loss
234
+
235
+
236
+ def optimize_parameters(self):
237
+ self.optimizer.zero_grad()
238
+ self.forward()
239
+ self.loss = self.get_loss(self.kd)
240
+ self.loss.backward()
241
+ self.optimizer.step()
242
+
243
+
244
+
245
+ def load_networks(self, model_path):
246
+ state_dict = torch.load(model_path, map_location=self.device)
247
+ model_state_dict = state_dict["model"]
248
+ optimizer_state_dict = state_dict["optimizer"]
249
+ model_state_dict = {k.replace("module.", ""): v for k, v in model_state_dict.items()}
250
+ optimizer_state_dict = {k.replace("module.", ""): v for k, v in optimizer_state_dict.items()}
251
+
252
+ if self.distributed:
253
+ self.student.module.load_state_dict(model_state_dict)
254
+ else:
255
+ self.student.load_state_dict(model_state_dict)
256
+ self.optimizer.load_state_dict(optimizer_state_dict)
257
+
258
+ print(f"Model loaded from {model_path}")
259
+ return True
260
+
261
+ @torch.no_grad()
262
+ def validate(self, gather=False, save=False, save_name=""):
263
+ self.student.eval()
264
+ y_pred = []
265
+ y_true = []
266
+ N_FAKE, N_REAL = 0, 0
267
+ for data, path in tqdm(self.val_loader, desc=f"Validation after {self.cur_epoch} epoch..."):
268
+ self.set_input(data, istrain=False)
269
+ self.forward()
270
+ pred = self.output['logit'].sigmoid()
271
+
272
+ if gather:
273
+ try:
274
+ dist
275
+ except:
276
+ import torch.distributed as dist
277
+ pred_gather = [pred for _ in range(self.world_size)]
278
+ label_gather = [self.label for _ in range(self.world_size)]
279
+ dist.all_gather(pred_gather, pred)
280
+ dist.all_gather(label_gather, self.label)
281
+ else:
282
+ pred_gather = [pred]
283
+ label_gather = [self.label]
284
+ N_FAKE += sum([(label == 1).sum().item() for label in label_gather])
285
+ N_REAL += sum([(label == 0).sum().item() for label in label_gather])
286
+
287
+ y_pred.extend(torch.cat(pred_gather).flatten().detach().cpu().tolist())
288
+ y_true.extend(torch.cat(label_gather).flatten().detach().cpu().tolist())
289
+
290
+ y_true, y_pred = np.array(y_true), np.array(y_pred)
291
+ acc = accuracy_score(y_true, y_pred > 0.5)
292
+ ap = average_precision_score(y_true, y_pred)
293
+ precision = precision_score(y_true, y_pred > 0.5)
294
+ if self.run:
295
+ self.run.log({"val_acc": acc, "val_ap": ap , "val_precision": precision})
296
+ self.run.log({"N_FAKE": N_FAKE, "N_REAL": N_REAL})
297
+ print(f"Validation: acc: {acc}, ap: {ap}, precision: {precision}")
298
+ print(f"N_FAKE: {N_FAKE}, N_REAL: {N_REAL}")
299
+ if save:
300
+ with open(save_name, "w") as f:
301
+ f.write(f"Validation: acc: {acc}, ap: {ap}, precision: {precision}\n")
302
+ f.write(f"N_FAKE: {N_FAKE}, N_REAL: {N_REAL}")
303
+
304
+
305
+ def train(self):
306
+ for epoch in range(self.cfg.nepoch):
307
+ if self.run:
308
+ self.run.log({"epoch": epoch})
309
+ if epoch % self.val_every == 0 and epoch != 0:
310
+ self.validate(gather=self.distributed)
311
+
312
+ self.student.train()
313
+ for data_and_paths in tqdm(self.train_loader, desc=f"Trainig {epoch} epoch..."):
314
+ data, path = data_and_paths
315
+ self.total_steps += 1
316
+ self.set_input(data)
317
+ self.optimize_parameters()
318
+ if self.total_steps % 100 == 0 and self.run:
319
+ print(f"step: {self.total_steps}, loss: {self.loss}")
320
+ self.run.log({"loss": self.loss, "step": self.total_steps})
321
+
322
+ if self.run:
323
+ self.save_networks(epoch)
324
+
325
+ if self.cfg.warmup:
326
+ self.scheduler.step()
327
+ if self.distributed:
328
+ dist.barrier()
329
+ self.cur_epoch = epoch
utils/utils.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import warnings
3
+ import numpy as np
4
+ import torch
5
+
6
+
7
+ warnings.filterwarnings("ignore", category=UserWarning, module="torch.nn.functional")
8
+
9
+
10
+ def str2bool(v: str, strict=True) -> bool:
11
+ if isinstance(v, bool):
12
+ return v
13
+ elif isinstance(v, str):
14
+ if v.lower() in ("true", "yes", "on" "t", "y", "1"):
15
+ return True
16
+ elif v.lower() in ("false", "no", "off", "f", "n", "0"):
17
+ return False
18
+ if strict:
19
+ raise argparse.ArgumentTypeError("Unsupported value encountered.")
20
+ else:
21
+ return True
22
+
23
+
24
+ def to_cuda(data, device="cuda", exclude_keys: "list[str]" = None):
25
+ if isinstance(data, torch.Tensor):
26
+ data = data.to(device)
27
+ elif isinstance(data, (tuple, list, set)):
28
+ data = [to_cuda(b, device) for b in data]
29
+ elif isinstance(data, dict):
30
+ if exclude_keys is None:
31
+ exclude_keys = []
32
+ for k in data.keys():
33
+ if k not in exclude_keys:
34
+ data[k] = to_cuda(data[k], device)
35
+ else:
36
+ # raise TypeError(f"Unsupported type: {type(data)}")
37
+ data = data
38
+ return data
39
+
40
+
41
+ def pad_img_to_square(img: np.ndarray):
42
+ H, W = img.shape[:2]
43
+ if H != W:
44
+ new_size = max(H, W)
45
+ img = np.pad(img, ((0, new_size - H), (0, new_size - W), (0, 0)), mode="constant")
46
+ assert img.shape[0] == img.shape[1] == new_size
47
+ return img
utils/warmup.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.optim.lr_scheduler import ReduceLROnPlateau, _LRScheduler
2
+
3
+
4
+ class GradualWarmupScheduler(_LRScheduler):
5
+ """Gradually warm-up(increasing) learning rate in optimizer.
6
+ Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'.
7
+
8
+ Args:
9
+ optimizer (Optimizer): Wrapped optimizer.
10
+ multiplier: target learning rate = base lr * multiplier if multiplier > 1.0. if multiplier = 1.0, lr starts from 0 and ends up with the base_lr.
11
+ total_epoch: target learning rate is reached at total_epoch, gradually
12
+ after_scheduler: after target_epoch, use this scheduler(eg. ReduceLROnPlateau)
13
+ """
14
+
15
+ def __init__(self, optimizer, multiplier, total_epoch, after_scheduler=None):
16
+ self.multiplier = multiplier
17
+ if self.multiplier < 1.0:
18
+ raise ValueError("multiplier should be greater thant or equal to 1.")
19
+ self.total_epoch = total_epoch
20
+ self.after_scheduler = after_scheduler
21
+ self.finished = False
22
+ super().__init__(optimizer)
23
+
24
+ def get_lr(self):
25
+ if self.last_epoch > self.total_epoch:
26
+ if self.after_scheduler:
27
+ if not self.finished:
28
+ self.after_scheduler.base_lrs = [base_lr * self.multiplier for base_lr in self.base_lrs]
29
+ self.finished = True
30
+ return self.after_scheduler.get_last_lr()
31
+ return [base_lr * self.multiplier for base_lr in self.base_lrs]
32
+
33
+ if self.multiplier == 1.0:
34
+ return [base_lr * (float(self.last_epoch) / self.total_epoch) for base_lr in self.base_lrs]
35
+ else:
36
+ return [
37
+ base_lr * ((self.multiplier - 1.0) * self.last_epoch / self.total_epoch + 1.0)
38
+ for base_lr in self.base_lrs
39
+ ]
40
+
41
+ def step_ReduceLROnPlateau(self, metrics, epoch=None):
42
+ if epoch is None:
43
+ epoch = self.last_epoch + 1
44
+ self.last_epoch = (
45
+ epoch if epoch != 0 else 1
46
+ ) # ReduceLROnPlateau is called at the end of epoch, whereas others are called at beginning
47
+ if self.last_epoch <= self.total_epoch:
48
+ warmup_lr = [
49
+ base_lr * ((self.multiplier - 1.0) * self.last_epoch / self.total_epoch + 1.0)
50
+ for base_lr in self.base_lrs
51
+ ]
52
+ for param_group, lr in zip(self.optimizer.param_groups, warmup_lr):
53
+ param_group["lr"] = lr
54
+ else:
55
+ if epoch is None:
56
+ self.after_scheduler.step(metrics, None)
57
+ else:
58
+ self.after_scheduler.step(metrics, epoch - self.total_epoch)
59
+
60
+ def step(self, epoch=None, metrics=None):
61
+ if type(self.after_scheduler) != ReduceLROnPlateau:
62
+ if self.finished and self.after_scheduler:
63
+ if epoch is None:
64
+ self.after_scheduler.step(None)
65
+ else:
66
+ self.after_scheduler.step(epoch - self.total_epoch)
67
+ else:
68
+ return super().step(epoch)
69
+ else:
70
+ self.step_ReduceLROnPlateau(metrics, epoch)