UPstud commited on
Commit
9f55d56
Β·
verified Β·
1 Parent(s): 7afba12

Delete Control-Color

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. Control-Color/CtrlColor_environ.yaml +0 -40
  2. Control-Color/annotator/__pycache__/util.cpython-38.pyc +0 -0
  3. Control-Color/annotator/util.py +0 -40
  4. Control-Color/app.py +0 -524
  5. Control-Color/cldm/__pycache__/cldm.cpython-38.pyc +0 -0
  6. Control-Color/cldm/__pycache__/ddim_haced_sag_step.cpython-38.pyc +0 -0
  7. Control-Color/cldm/__pycache__/hack.cpython-310.pyc +0 -0
  8. Control-Color/cldm/__pycache__/hack.cpython-38.pyc +0 -0
  9. Control-Color/cldm/__pycache__/model.cpython-38.pyc +0 -0
  10. Control-Color/cldm/cldm.py +0 -547
  11. Control-Color/cldm/ddim_haced_sag_step.py +0 -494
  12. Control-Color/cldm/ddim_hacked_sag.py +0 -543
  13. Control-Color/cldm/hack.py +0 -111
  14. Control-Color/cldm/model.py +0 -28
  15. Control-Color/config.py +0 -1
  16. Control-Color/ldm/__pycache__/util.cpython-38.pyc +0 -0
  17. Control-Color/ldm/models/__pycache__/autoencoder.cpython-38.pyc +0 -0
  18. Control-Color/ldm/models/__pycache__/autoencoder_train.cpython-38.pyc +0 -0
  19. Control-Color/ldm/models/autoencoder.py +0 -220
  20. Control-Color/ldm/models/autoencoder_train.py +0 -299
  21. Control-Color/ldm/models/diffusion/__init__.py +0 -0
  22. Control-Color/ldm/models/diffusion/__pycache__/__init__.cpython-38.pyc +0 -0
  23. Control-Color/ldm/models/diffusion/__pycache__/ddim.cpython-38.pyc +0 -0
  24. Control-Color/ldm/models/diffusion/__pycache__/ddpm.cpython-38.pyc +0 -0
  25. Control-Color/ldm/models/diffusion/__pycache__/ddpm_nonoise.cpython-38.pyc +0 -0
  26. Control-Color/ldm/models/diffusion/ddim.py +0 -337
  27. Control-Color/ldm/models/diffusion/ddpm.py +0 -1911
  28. Control-Color/ldm/models/diffusion/dpm_solver/__init__.py +0 -1
  29. Control-Color/ldm/models/diffusion/dpm_solver/dpm_solver.py +0 -1154
  30. Control-Color/ldm/models/diffusion/dpm_solver/sampler.py +0 -87
  31. Control-Color/ldm/models/diffusion/plms.py +0 -244
  32. Control-Color/ldm/models/diffusion/sampling_util.py +0 -22
  33. Control-Color/ldm/models/logger.py +0 -93
  34. Control-Color/ldm/modules/__pycache__/attention.cpython-38.pyc +0 -0
  35. Control-Color/ldm/modules/__pycache__/attention_dcn_control.cpython-38.pyc +0 -0
  36. Control-Color/ldm/modules/__pycache__/ema.cpython-38.pyc +0 -0
  37. Control-Color/ldm/modules/attention.py +0 -653
  38. Control-Color/ldm/modules/attention_dcn_control.py +0 -854
  39. Control-Color/ldm/modules/diffusionmodules/__init__.py +0 -0
  40. Control-Color/ldm/modules/diffusionmodules/__pycache__/__init__.cpython-38.pyc +0 -0
  41. Control-Color/ldm/modules/diffusionmodules/__pycache__/model.cpython-38.pyc +0 -0
  42. Control-Color/ldm/modules/diffusionmodules/__pycache__/model_brefore_dcn.cpython-38.pyc +0 -0
  43. Control-Color/ldm/modules/diffusionmodules/__pycache__/openaimodel.cpython-38.pyc +0 -0
  44. Control-Color/ldm/modules/diffusionmodules/__pycache__/util.cpython-38.pyc +0 -0
  45. Control-Color/ldm/modules/diffusionmodules/model.py +0 -1107
  46. Control-Color/ldm/modules/diffusionmodules/model_brefore_dcn.py +0 -852
  47. Control-Color/ldm/modules/diffusionmodules/openaimodel.py +0 -853
  48. Control-Color/ldm/modules/diffusionmodules/util.py +0 -270
  49. Control-Color/ldm/modules/distributions/__init__.py +0 -0
  50. Control-Color/ldm/modules/distributions/__pycache__/__init__.cpython-38.pyc +0 -0
Control-Color/CtrlColor_environ.yaml DELETED
@@ -1,40 +0,0 @@
1
- name: CtrlColor
2
- channels:
3
- - pytorch
4
- - defaults
5
- dependencies:
6
- - python=3.8.5
7
- - pip=20.3
8
- - cudatoolkit=11.3
9
- - pytorch=1.12.1
10
- - torchvision=0.13.1
11
- - numpy=1.23.1
12
- - pip:
13
- - gradio==3.31.0
14
- - gradio-client==0.2.5
15
- - albumentations==1.3.0
16
- - opencv-python==4.9.0.80
17
- - opencv-python-headless==4.5.5.64
18
- - imageio==2.9.0
19
- - imageio-ffmpeg==0.4.2
20
- - pytorch-lightning==1.5.0
21
- - omegaconf==2.1.1
22
- - test-tube>=0.7.5
23
- - streamlit==1.12.1
24
- - webdataset==0.2.5
25
- - kornia==0.6
26
- - open_clip_torch==2.0.2
27
- - invisible-watermark>=0.1.5
28
- - streamlit-drawable-canvas==0.8.0
29
- - torchmetrics==0.6.0
30
- - addict==2.4.0
31
- - yapf==0.32.0
32
- - prettytable==3.6.0
33
- - basicsr==1.4.2
34
- - salesforce-lavis==1.0.2
35
- - grpcio==1.60
36
- - pydantic==1.10.5
37
- - spacy==3.5.1
38
- - typer==0.7.0
39
- - typing-extensions==4.4.0
40
- - fastapi==0.92.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/annotator/__pycache__/util.cpython-38.pyc DELETED
Binary file (1.35 kB)
 
Control-Color/annotator/util.py DELETED
@@ -1,40 +0,0 @@
1
- import numpy as np
2
- import cv2
3
- import os
4
-
5
-
6
- annotator_ckpts_path = os.path.join(os.path.dirname(__file__), 'ckpts')
7
-
8
-
9
- def HWC3(x):
10
- assert x.dtype == np.uint8
11
- if x.ndim == 2:
12
- x = x[:, :, None]
13
- assert x.ndim == 3
14
- H, W, C = x.shape
15
- assert C == 1 or C == 3 or C == 4
16
- if C == 3:
17
- return x
18
- if C == 1:
19
- return np.concatenate([x, x, x], axis=2)
20
- if C == 4:
21
- color = x[:, :, 0:3].astype(np.float32)
22
- alpha = x[:, :, 3:4].astype(np.float32) / 255.0
23
- y = color * alpha + 255.0 * (1.0 - alpha)
24
- y = y.clip(0, 255).astype(np.uint8)
25
- return y
26
-
27
-
28
- def resize_image(input_image, resolution):
29
- H, W, C = input_image.shape
30
- H = float(H)
31
- W = float(W)
32
- k = float(resolution) / min(H, W)#min(H,W)
33
- H *= k
34
- W *= k
35
- H_new = int(np.round(H / 64.0)) * 64
36
- W_new = int(np.round(W / 64.0)) * 64
37
- H = H_new if H_new<800 else int(np.round(800 / 64.0)) * 64#1024->896
38
- W=W_new if W_new<800 else int(np.round(800 / 64.0)) * 64
39
- img = cv2.resize(input_image, (W, H), interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA)
40
- return img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/app.py DELETED
@@ -1,524 +0,0 @@
1
- import os
2
- from share import *
3
- import config
4
-
5
- import cv2
6
- import einops
7
- import gradio as gr
8
- import numpy as np
9
- import torch
10
- import random
11
-
12
- from pytorch_lightning import seed_everything
13
- from annotator.util import resize_image
14
- from cldm.model import create_model, load_state_dict
15
- from cldm.ddim_haced_sag_step import DDIMSampler
16
- from lavis.models import load_model_and_preprocess
17
- from PIL import Image
18
- import tqdm
19
-
20
- from ldm.models.autoencoder_train import AutoencoderKL
21
-
22
- ckpt_path="./pretrained_models/main_model.ckpt"
23
-
24
- model = create_model('./models/cldm_v15_inpainting_infer1.yaml').cpu()
25
- model.load_state_dict(load_state_dict(ckpt_path, location='cuda'),strict=False)
26
- model = model.cuda()
27
-
28
- ddim_sampler = DDIMSampler(model)
29
-
30
-
31
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
32
- BLIP_model, vis_processors, _ = load_model_and_preprocess(name="blip_caption", model_type="base_coco", is_eval=True, device=device)
33
-
34
- vae_model_ckpt_path="./pretrained_models/content-guided_deformable_vae.ckpt"
35
-
36
- def load_vae():
37
- init_config = {
38
- "embed_dim": 4,
39
- "monitor": "val/rec_loss",
40
- "ddconfig":{
41
- "double_z": True,
42
- "z_channels": 4,
43
- "resolution": 256,
44
- "in_channels": 3,
45
- "out_ch": 3,
46
- "ch": 128,
47
- "ch_mult":[1,2,4,4],
48
- "num_res_blocks": 2,
49
- "attn_resolutions": [],
50
- "dropout": 0.0,
51
- },
52
- "lossconfig":{
53
- "target": "ldm.modules.losses.LPIPSWithDiscriminator",
54
- "params":{
55
- "disc_start": 501,
56
- "kl_weight": 0,
57
- "disc_weight": 0.025,
58
- "disc_factor": 1.0
59
- }
60
- }
61
- }
62
- vae = AutoencoderKL(**init_config)
63
- vae.load_state_dict(load_state_dict(vae_model_ckpt_path, location='cuda'))
64
- vae = vae.cuda()
65
- return vae
66
-
67
- vae_model=load_vae()
68
-
69
- def encode_mask(mask,masked_image):
70
- mask = torch.nn.functional.interpolate(mask, size=(mask.shape[2] // 8, mask.shape[3] // 8))
71
- # mask=torch.cat([mask] * 2) #if do_classifier_free_guidance else mask
72
- mask = mask.to(device="cuda")
73
- # do_classifier_free_guidance=False
74
- masked_image_latents = model.get_first_stage_encoding(model.encode_first_stage(masked_image.cuda())).detach()
75
- return mask,masked_image_latents
76
-
77
- def get_mask(input_image,hint_image):
78
- mask=input_image.copy()
79
- H,W,C=input_image.shape
80
- for i in range(H):
81
- for j in range(W):
82
- if input_image[i,j,0]==hint_image[i,j,0]:
83
- # print(input_image[i,j,0])
84
- mask[i,j,:]=255.
85
- else:
86
- mask[i,j,:]=0. #input_image[i,j,:]
87
- kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
88
- mask=cv2.morphologyEx(np.array(mask),cv2.MORPH_OPEN,kernel,iterations=1)
89
- return mask
90
-
91
- def prepare_mask_and_masked_image(image, mask):
92
- """
93
- Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be
94
- converted to ``torch.Tensor`` with shapes ``batch x channels x height x width`` where ``channels`` is ``3`` for the
95
- ``image`` and ``1`` for the ``mask``.
96
- The ``image`` will be converted to ``torch.float32`` and normalized to be in ``[-1, 1]``. The ``mask`` will be
97
- binarized (``mask > 0.5``) and cast to ``torch.float32`` too.
98
- Args:
99
- image (Union[np.array, PIL.Image, torch.Tensor]): The image to inpaint.
100
- It can be a ``PIL.Image``, or a ``height x width x 3`` ``np.array`` or a ``channels x height x width``
101
- ``torch.Tensor`` or a ``batch x channels x height x width`` ``torch.Tensor``.
102
- mask (_type_): The mask to apply to the image, i.e. regions to inpaint.
103
- It can be a ``PIL.Image``, or a ``height x width`` ``np.array`` or a ``1 x height x width``
104
- ``torch.Tensor`` or a ``batch x 1 x height x width`` ``torch.Tensor``.
105
- Raises:
106
- ValueError: ``torch.Tensor`` images should be in the ``[-1, 1]`` range. ValueError: ``torch.Tensor`` mask
107
- should be in the ``[0, 1]`` range. ValueError: ``mask`` and ``image`` should have the same spatial dimensions.
108
- TypeError: ``mask`` is a ``torch.Tensor`` but ``image`` is not
109
- (ot the other way around).
110
- Returns:
111
- tuple[torch.Tensor]: The pair (mask, masked_image) as ``torch.Tensor`` with 4
112
- dimensions: ``batch x channels x height x width``.
113
- """
114
- if isinstance(image, torch.Tensor):
115
- if not isinstance(mask, torch.Tensor):
116
- raise TypeError(f"`image` is a torch.Tensor but `mask` (type: {type(mask)} is not")
117
-
118
- # Batch single image
119
- if image.ndim == 3:
120
- assert image.shape[0] == 3, "Image outside a batch should be of shape (3, H, W)"
121
- image = image.unsqueeze(0)
122
-
123
- # Batch and add channel dim for single mask
124
- if mask.ndim == 2:
125
- mask = mask.unsqueeze(0).unsqueeze(0)
126
-
127
- # Batch single mask or add channel dim
128
- if mask.ndim == 3:
129
- # Single batched mask, no channel dim or single mask not batched but channel dim
130
- if mask.shape[0] == 1:
131
- mask = mask.unsqueeze(0)
132
-
133
- # Batched masks no channel dim
134
- else:
135
- mask = mask.unsqueeze(1)
136
-
137
- assert image.ndim == 4 and mask.ndim == 4, "Image and Mask must have 4 dimensions"
138
- assert image.shape[-2:] == mask.shape[-2:], "Image and Mask must have the same spatial dimensions"
139
- assert image.shape[0] == mask.shape[0], "Image and Mask must have the same batch size"
140
-
141
- # Check image is in [-1, 1]
142
- if image.min() < -1 or image.max() > 1:
143
- raise ValueError("Image should be in [-1, 1] range")
144
-
145
- # Check mask is in [0, 1]
146
- if mask.min() < 0 or mask.max() > 1:
147
- raise ValueError("Mask should be in [0, 1] range")
148
-
149
- # Binarize mask
150
- mask[mask < 0.5] = 0
151
- mask[mask >= 0.5] = 1
152
-
153
- # Image as float32
154
- image = image.to(dtype=torch.float32)
155
- elif isinstance(mask, torch.Tensor):
156
- raise TypeError(f"`mask` is a torch.Tensor but `image` (type: {type(image)} is not")
157
- else:
158
- # preprocess image
159
- if isinstance(image, (Image.Image, np.ndarray)):
160
- image = [image]
161
-
162
- if isinstance(image, list) and isinstance(image[0], Image.Image):
163
- image = [np.array(i.convert("RGB"))[None, :] for i in image]
164
- image = np.concatenate(image, axis=0)
165
- elif isinstance(image, list) and isinstance(image[0], np.ndarray):
166
- image = np.concatenate([i[None, :] for i in image], axis=0)
167
-
168
- image = image.transpose(0, 3, 1, 2)
169
- image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
170
-
171
- # preprocess mask
172
- if isinstance(mask, (Image.Image, np.ndarray)):
173
- mask = [mask]
174
-
175
- if isinstance(mask, list) and isinstance(mask[0], Image.Image):
176
- mask = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask], axis=0)
177
- mask = mask.astype(np.float32) / 255.0
178
- elif isinstance(mask, list) and isinstance(mask[0], np.ndarray):
179
- mask = np.concatenate([m[None, None, :] for m in mask], axis=0)
180
-
181
- mask[mask < 0.5] = 0
182
- mask[mask >= 0.5] = 1
183
- mask = torch.from_numpy(mask)
184
-
185
- masked_image = image * (mask < 0.5)
186
-
187
- return mask, masked_image
188
-
189
- # generate image
190
- generator = torch.manual_seed(859311133)#0
191
- def path2L(img_path):
192
- raw_image = cv2.imread(img_path)
193
- raw_image = cv2.cvtColor(raw_image,cv2.COLOR_BGR2LAB)
194
- raw_image_input = cv2.merge([raw_image[:,:,0],raw_image[:,:,0],raw_image[:,:,0]])
195
- return raw_image_input
196
-
197
- def is_gray_scale(img, threshold=10):
198
- img = Image.fromarray(img)
199
- if len(img.getbands()) == 1:
200
- return True
201
- img1 = np.asarray(img.getchannel(channel=0), dtype=np.int16)
202
- img2 = np.asarray(img.getchannel(channel=1), dtype=np.int16)
203
- img3 = np.asarray(img.getchannel(channel=2), dtype=np.int16)
204
- diff1 = (img1 - img2).var()
205
- diff2 = (img2 - img3).var()
206
- diff3 = (img3 - img1).var()
207
- diff_sum = (diff1 + diff2 + diff3) / 3.0
208
- if diff_sum <= threshold:
209
- return True
210
- else:
211
- return False
212
-
213
- def randn_tensor(
214
- shape,
215
- generator= None,
216
- device= None,
217
- dtype=None,
218
- layout= None,
219
- ):
220
- """A helper function to create random tensors on the desired `device` with the desired `dtype`. When
221
- passing a list of generators, you can seed each batch size individually. If CPU generators are passed, the tensor
222
- is always created on the CPU.
223
- """
224
- # device on which tensor is created defaults to device
225
- rand_device = device
226
- batch_size = shape[0]
227
-
228
- layout = layout or torch.strided
229
- device = device or torch.device("cpu")
230
-
231
- if generator is not None:
232
- gen_device_type = generator.device.type if not isinstance(generator, list) else generator[0].device.type
233
- if gen_device_type != device.type and gen_device_type == "cpu":
234
- rand_device = "cpu"
235
- if device != "mps":
236
- print("The passed generator was created on 'cpu' even though a tensor on {device} was expected.")
237
- # logger.info(
238
- # f"The passed generator was created on 'cpu' even though a tensor on {device} was expected."
239
- # f" Tensors will be created on 'cpu' and then moved to {device}. Note that one can probably"
240
- # f" slighly speed up this function by passing a generator that was created on the {device} device."
241
- # )
242
- elif gen_device_type != device.type and gen_device_type == "cuda":
243
- raise ValueError(f"Cannot generate a {device} tensor from a generator of type {gen_device_type}.")
244
-
245
- # make sure generator list of length 1 is treated like a non-list
246
- if isinstance(generator, list) and len(generator) == 1:
247
- generator = generator[0]
248
-
249
- if isinstance(generator, list):
250
- shape = (1,) + shape[1:]
251
- latents = [
252
- torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype, layout=layout)
253
- for i in range(batch_size)
254
- ]
255
- latents = torch.cat(latents, dim=0).to(device)
256
- else:
257
- latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype, layout=layout).to(device)
258
-
259
- return latents
260
-
261
- def add_noise(
262
- original_samples: torch.FloatTensor,
263
- noise: torch.FloatTensor,
264
- timesteps: torch.IntTensor,
265
- ) -> torch.FloatTensor:
266
- betas = torch.linspace(0.00085, 0.0120, 1000, dtype=torch.float32)
267
- alphas = 1.0 - betas
268
- alphas_cumprod = torch.cumprod(alphas, dim=0)
269
- alphas_cumprod = alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
270
- timesteps = timesteps.to(original_samples.device)
271
-
272
- sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
273
- sqrt_alpha_prod = sqrt_alpha_prod.flatten()
274
- while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
275
- sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
276
-
277
- sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
278
- sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
279
- while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
280
- sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
281
-
282
- noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
283
-
284
- return noisy_samples
285
-
286
- def set_timesteps(num_inference_steps: int, timestep_spacing="leading",device=None):
287
- """
288
- Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.
289
-
290
- Args:
291
- num_inference_steps (`int`):
292
- the number of diffusion steps used when generating samples with a pre-trained model.
293
- """
294
- num_train_timesteps=1000
295
- if num_inference_steps > num_train_timesteps:
296
- raise ValueError(
297
- f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
298
- f" {num_train_timesteps} as the unet model trained with this scheduler can only handle"
299
- f" maximal {num_train_timesteps} timesteps."
300
- )
301
-
302
- num_inference_steps = num_inference_steps
303
- # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
304
- if timestep_spacing == "linspace":
305
- timesteps = (
306
- np.linspace(0, num_train_timesteps - 1, num_inference_steps)
307
- .round()[::-1]
308
- .copy()
309
- .astype(np.int64)
310
- )
311
- elif timestep_spacing == "leading":
312
- step_ratio = num_train_timesteps // num_inference_steps
313
- # creates integer timesteps by multiplying by ratio
314
- # casting to int to avoid issues when num_inference_step is power of 3
315
- timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].copy().astype(np.int64)
316
- # timesteps += steps_offset
317
- elif timestep_spacing == "trailing":
318
- step_ratio = num_train_timesteps / num_inference_steps
319
- # creates integer timesteps by multiplying by ratio
320
- # casting to int to avoid issues when num_inference_step is power of 3
321
- timesteps = np.round(np.arange(num_train_timesteps, 0, -step_ratio)).astype(np.int64)
322
- timesteps -= 1
323
- else:
324
- raise ValueError(
325
- f"{timestep_spacing} is not supported. Please make sure to choose one of 'leading' or 'trailing'."
326
- )
327
-
328
- timesteps = torch.from_numpy(timesteps).to(device)
329
- return timesteps
330
-
331
- def get_timesteps(num_inference_steps, timesteps_set, strength, device):
332
- # get the original timestep using init_timestep
333
- init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
334
-
335
- t_start = max(num_inference_steps - init_timestep, 0)
336
- timesteps = timesteps_set[t_start * 1 :]
337
-
338
- return timesteps, num_inference_steps - t_start
339
-
340
-
341
- def get_noised_image_latents(img,W,H,ddim_steps,strength,seed,device):
342
- img1 = [cv2.resize(img,(W,H))]
343
- img1 = np.concatenate([i[None, :] for i in img1], axis=0)
344
- img1 = img1.transpose(0, 3, 1, 2)
345
- img1 = torch.from_numpy(img1).to(dtype=torch.float32) /127.5 - 1.0
346
-
347
- image_latents=model.get_first_stage_encoding(model.encode_first_stage(img1.cuda())).detach()
348
- shape=image_latents.shape
349
- generator = torch.manual_seed(seed)
350
-
351
- noise = randn_tensor(shape, generator=generator, device=device, dtype=torch.float32)
352
-
353
- timesteps_set=set_timesteps(ddim_steps,timestep_spacing="linspace", device=device)
354
- timesteps, num_inference_steps = get_timesteps(ddim_steps, timesteps_set, strength, device)
355
- latent_timestep = timesteps[1].repeat(1 * 1)
356
-
357
- init_latents = add_noise(image_latents, noise, torch.tensor(latent_timestep))
358
- for j in range(0, 1000, 100):
359
-
360
- x_samples=model.decode_first_stage(add_noise(image_latents, noise, torch.tensor(j)))
361
- init_image=(einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
362
-
363
- cv2.imwrite("./initlatents1/"+str(j)+"init_image.png",cv2.cvtColor(init_image[0],cv2.COLOR_RGB2BGR))
364
- return init_latents
365
-
366
- def process(using_deformable_vae,change_according_to_strokes,iterative_editing,input_image,hint_image,prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, sag_scale,SAG_influence_step, seed, eta):
367
- torch.cuda.empty_cache()
368
- with torch.no_grad():
369
- ref_flag=True
370
- input_image_ori=input_image
371
- if is_gray_scale(input_image):
372
- print("It is a greyscale image.")
373
- # mask=get_mask(input_image,hint_image)
374
- else:
375
- print("It is a color image.")
376
- input_image_ori=input_image
377
- input_image=cv2.cvtColor(input_image,cv2.COLOR_RGB2LAB)[:,:,0]
378
- input_image=cv2.merge([input_image,input_image,input_image])
379
- mask=get_mask(input_image_ori,hint_image)
380
- cv2.imwrite("gradio_mask1.png",mask)
381
-
382
- if iterative_editing:
383
- mask=255-mask
384
- if change_according_to_strokes:
385
- hint_image=mask/255.*hint_image+(1-mask/255.)*input_image_ori
386
- else:
387
- hint_image=mask/255.*input_image+(1-mask/255.)*input_image_ori
388
- else:
389
- hint_image=mask/255.*input_image+(1-mask/255.)*hint_image
390
- hint_image=hint_image.astype(np.uint8)
391
- if len(prompt)==0:
392
- image = Image.fromarray(input_image)
393
- image = vis_processors["eval"](image).unsqueeze(0).to(device)
394
- prompt = BLIP_model.generate({"image": image})[0]
395
- if "a black and white photo of" in prompt or "black and white photograph of" in prompt:
396
- prompt=prompt.replace(prompt[:prompt.find("of")+3],"")
397
- print(prompt)
398
- H_ori,W_ori,C_ori=input_image.shape
399
- img = resize_image(input_image, image_resolution)
400
- mask = resize_image(mask, image_resolution)
401
- hint_image =resize_image(hint_image,image_resolution)
402
- mask,masked_image=prepare_mask_and_masked_image(Image.fromarray(hint_image),Image.fromarray(mask))
403
- mask,masked_image_latents=encode_mask(mask,masked_image)
404
- H, W, C = img.shape
405
-
406
- # if ref_image is None:
407
- ref_image=np.array([[[0]*C]*W]*H).astype(np.float32)
408
- # print(ref_image.shape)
409
- # ref_flag=False
410
- ref_image=resize_image(ref_image,image_resolution)
411
-
412
- # cv2.imwrite("exemplar_image.png",cv2.cvtColor(ref_image,cv2.COLOR_RGB2BGR))
413
-
414
- # ddim_steps=1
415
- control = torch.from_numpy(img.copy()).float().cuda() / 255.0
416
- control = torch.stack([control for _ in range(num_samples)], dim=0)
417
- control = einops.rearrange(control, 'b h w c -> b c h w').clone()
418
-
419
- if seed == -1:
420
- seed = random.randint(0, 65535)
421
- seed_everything(seed)
422
-
423
- ref_image=cv2.resize(ref_image,(W,H))
424
-
425
- ref_image=torch.from_numpy(ref_image).cuda().unsqueeze(0)
426
-
427
- init_latents=None
428
-
429
- if config.save_memory:
430
- model.low_vram_shift(is_diffusing=False)
431
-
432
- print("no reference images, using Frozen encoder")
433
- cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
434
- un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
435
- shape = (4, H // 8, W // 8)
436
-
437
- if config.save_memory:
438
- model.low_vram_shift(is_diffusing=True)
439
- noise = randn_tensor(shape, generator=generator, device=device, dtype=torch.float32)
440
- model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
441
- samples, intermediates = ddim_sampler.sample(model,ddim_steps, num_samples,
442
- shape, cond, mask=mask, masked_image_latents=masked_image_latents,verbose=False, eta=eta,
443
- # x_T=image_latents,
444
- x_T=init_latents,
445
- unconditional_guidance_scale=scale,
446
- sag_scale = sag_scale,
447
- SAG_influence_step=SAG_influence_step,
448
- noise = noise,
449
- unconditional_conditioning=un_cond)
450
-
451
-
452
- if config.save_memory:
453
- model.low_vram_shift(is_diffusing=False)
454
-
455
- if not using_deformable_vae:
456
- x_samples = model.decode_first_stage(samples)
457
- else:
458
- samples = model.decode_first_stage_before_vae(samples)
459
- gray_content_z=vae_model.get_gray_content_z(torch.from_numpy(img.copy()).float().cuda() / 255.0)
460
- # print(gray_content_z.shape)
461
- x_samples = vae_model.decode(samples,gray_content_z)
462
-
463
- x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
464
-
465
- #single image replace L channel
466
- results_ori = [x_samples[i] for i in range(num_samples)]
467
- results_ori=[cv2.resize(i,(W_ori,H_ori),interpolation=cv2.INTER_LANCZOS4) for i in results_ori]
468
-
469
- cv2.imwrite("result_ori.png",cv2.cvtColor(results_ori[0],cv2.COLOR_RGB2BGR))
470
-
471
- results_tmp=[cv2.cvtColor(np.array(i),cv2.COLOR_RGB2LAB) for i in results_ori]
472
- results=[cv2.merge([input_image[:,:,0],tmp[:,:,1],tmp[:,:,2]]) for tmp in results_tmp]
473
- results_mergeL=[cv2.cvtColor(np.asarray(i),cv2.COLOR_LAB2RGB) for i in results]#cv2.COLOR_LAB2BGR)
474
- cv2.imwrite("output.png",cv2.cvtColor(results_mergeL[0],cv2.COLOR_RGB2BGR))
475
- return results_mergeL
476
-
477
- def get_grayscale_img(img, progress=gr.Progress(track_tqdm=True)):
478
- torch.cuda.empty_cache()
479
- for j in tqdm.tqdm(range(1),desc="Uploading input..."):
480
- return img,"Uploading input image done."
481
-
482
- block = gr.Blocks().queue()
483
- with block:
484
- with gr.Row():
485
- gr.Markdown("## Control-Color")#("## Color-Anything")#Control Stable Diffusion with L channel
486
- with gr.Row():
487
- with gr.Column():
488
- # input_image = gr.Image(source='upload', type="numpy")
489
- grayscale_img = gr.Image(visible=False, type="numpy")
490
- input_image = gr.Image(source='upload',tool='color-sketch',interactive=True)
491
- Grayscale_button = gr.Button(value="Upload input image")
492
- text_out = gr.Textbox(value="Please upload input image first, then draw the strokes or input text prompts or give reference images as you wish.")
493
- prompt = gr.Textbox(label="Prompt")
494
- change_according_to_strokes = gr.Checkbox(label='Change according to strokes\' color', value=True)
495
- iterative_editing = gr.Checkbox(label='Only change the strokes\' area', value=False)
496
- using_deformable_vae = gr.Checkbox(label='Using deformable vae. (Less color overflow)', value=False)
497
- # with gr.Accordion("Input Reference", open=False):
498
- # ref_image = gr.Image(source='upload', type="numpy")
499
- run_button = gr.Button(label="Upload prompts/strokes (optional) and Run",value="Upload prompts/strokes (optional) and Run")
500
- with gr.Accordion("Advanced options", open=False):
501
- num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
502
- image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
503
- strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
504
- guess_mode = gr.Checkbox(label='Guess Mode', value=False)
505
- #detect_resolution = gr.Slider(label="Depth Resolution", minimum=128, maximum=1024, value=384, step=1)
506
- ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
507
- scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=7.0, step=0.1)#value=9.0
508
- sag_scale = gr.Slider(label="SAG Scale", minimum=0.0, maximum=1.0, value=0.05, step=0.01)#0.08
509
- SAG_influence_step = gr.Slider(label="1000-SAG influence step", minimum=0, maximum=900, value=600, step=50)
510
- seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)#94433242802
511
- eta = gr.Number(label="eta (DDIM)", value=0.0)
512
- a_prompt = gr.Textbox(label="Added Prompt", value='best quality, detailed, real')#extremely detailed
513
- n_prompt = gr.Textbox(label="Negative Prompt",
514
- value='a black and white photo, longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
515
- with gr.Column():
516
- result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
517
- # grayscale_img = gr.Image(interactive=False,visible=False)
518
-
519
- Grayscale_button.click(fn=get_grayscale_img,inputs=input_image,outputs=[grayscale_img,text_out])
520
- ips = [using_deformable_vae,change_according_to_strokes,iterative_editing,grayscale_img,input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale,sag_scale,SAG_influence_step, seed, eta]
521
- run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
522
-
523
-
524
- block.launch(server_name='0.0.0.0',share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/cldm/__pycache__/cldm.cpython-38.pyc DELETED
Binary file (12 kB)
 
Control-Color/cldm/__pycache__/ddim_haced_sag_step.cpython-38.pyc DELETED
Binary file (13.3 kB)
 
Control-Color/cldm/__pycache__/hack.cpython-310.pyc DELETED
Binary file (3.88 kB)
 
Control-Color/cldm/__pycache__/hack.cpython-38.pyc DELETED
Binary file (3.89 kB)
 
Control-Color/cldm/__pycache__/model.cpython-38.pyc DELETED
Binary file (1.09 kB)
 
Control-Color/cldm/cldm.py DELETED
@@ -1,547 +0,0 @@
1
- import einops
2
- import torch
3
- import torch as th
4
- import torch.nn as nn
5
-
6
- from ldm.modules.diffusionmodules.util import (
7
- conv_nd,
8
- linear,
9
- zero_module,
10
- timestep_embedding,
11
- )
12
-
13
- from einops import rearrange, repeat
14
- from torchvision.utils import make_grid
15
- from ldm.modules.attention import SpatialTransformer
16
- from ldm.modules.attention_dcn_control import SpatialTransformer_dcn
17
- from ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock
18
- from ldm.models.diffusion.ddpm import LatentDiffusion
19
- from ldm.util import log_txt_as_img, exists, instantiate_from_config
20
- from ldm.models.diffusion.ddim import DDIMSampler
21
-
22
-
23
- class ControlledUnetModel(UNetModel):
24
- def forward(self, x, timesteps=None, context=None, control=None, only_mid_control=False, **kwargs):
25
- hs = []
26
- # print("timestep",timesteps)
27
- with torch.no_grad():
28
- t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
29
- # print("t_emb",t_emb)
30
- emb = self.time_embed(t_emb)
31
- h = x.type(self.dtype)
32
- for module in self.input_blocks:
33
- h = module(h, emb, context)#,timestep=timesteps)
34
- hs.append(h)
35
- h = self.middle_block(h, emb, context)#,timestep=timesteps)
36
-
37
- if control is not None:
38
- h += control.pop()
39
-
40
- for i, module in enumerate(self.output_blocks):
41
- # print("output_blocks0",h.shape)
42
- if only_mid_control or control is None:
43
- h = torch.cat([h, hs.pop()], dim=1)
44
- else:
45
- h = torch.cat([h, hs.pop() + control.pop()], dim=1)
46
- h = module(h, emb, context)#,timestep=timesteps)
47
-
48
- # print("output_blocks",h.shape)
49
-
50
- h = h.type(x.dtype)
51
- h=self.out(h)
52
- # print("self.ot",h.shape)
53
- return h
54
-
55
-
56
- class ControlNet(nn.Module):
57
- def __init__(
58
- self,
59
- image_size,
60
- in_channels,
61
- model_channels,
62
- hint_channels,
63
- num_res_blocks,
64
- attention_resolutions,
65
- dropout=0,
66
- channel_mult=(1, 2, 4, 8),
67
- conv_resample=True,
68
- dims=2,
69
- use_checkpoint=False,
70
- use_fp16=False,
71
- num_heads=-1,
72
- num_head_channels=-1,
73
- num_heads_upsample=-1,
74
- use_scale_shift_norm=False,
75
- resblock_updown=False,
76
- use_new_attention_order=False,
77
- use_spatial_transformer=False, # custom transformer support
78
- transformer_depth=1, # custom transformer support
79
- context_dim=None, # custom transformer support
80
- n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
81
- legacy=True,
82
- disable_self_attentions=None,
83
- num_attention_blocks=None,
84
- disable_middle_self_attn=False,
85
- use_linear_in_transformer=False,
86
- ):
87
- super().__init__()
88
- if use_spatial_transformer:
89
- assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
90
-
91
- if context_dim is not None:
92
- assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
93
- from omegaconf.listconfig import ListConfig
94
- if type(context_dim) == ListConfig:
95
- context_dim = list(context_dim)
96
-
97
- if num_heads_upsample == -1:
98
- num_heads_upsample = num_heads
99
-
100
- if num_heads == -1:
101
- assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
102
-
103
- if num_head_channels == -1:
104
- assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
105
-
106
- self.dims = dims
107
- self.image_size = image_size
108
- self.in_channels = in_channels
109
- self.model_channels = model_channels
110
- if isinstance(num_res_blocks, int):
111
- self.num_res_blocks = len(channel_mult) * [num_res_blocks]
112
- else:
113
- if len(num_res_blocks) != len(channel_mult):
114
- raise ValueError("provide num_res_blocks either as an int (globally constant) or "
115
- "as a list/tuple (per-level) with the same length as channel_mult")
116
- self.num_res_blocks = num_res_blocks
117
- if disable_self_attentions is not None:
118
- # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
119
- assert len(disable_self_attentions) == len(channel_mult)
120
- if num_attention_blocks is not None:
121
- assert len(num_attention_blocks) == len(self.num_res_blocks)
122
- assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
123
- print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
124
- f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
125
- f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
126
- f"attention will still not be set.")
127
-
128
- self.attention_resolutions = attention_resolutions
129
- self.dropout = dropout
130
- self.channel_mult = channel_mult
131
- self.conv_resample = conv_resample
132
- self.use_checkpoint = use_checkpoint
133
- self.dtype = th.float16 if use_fp16 else th.float32
134
- self.num_heads = num_heads
135
- self.num_head_channels = num_head_channels
136
- self.num_heads_upsample = num_heads_upsample
137
- self.predict_codebook_ids = n_embed is not None
138
-
139
- time_embed_dim = model_channels * 4
140
- self.time_embed = nn.Sequential(
141
- linear(model_channels, time_embed_dim),
142
- nn.SiLU(),
143
- linear(time_embed_dim, time_embed_dim),
144
- )
145
-
146
- self.input_blocks = nn.ModuleList(
147
- [
148
- TimestepEmbedSequential(
149
- conv_nd(dims, in_channels, model_channels, 3, padding=1)
150
- )
151
- ]
152
- )
153
- self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels)])
154
-
155
- self.input_hint_block = TimestepEmbedSequential(
156
- conv_nd(dims, hint_channels, 16, 3, padding=1),
157
- nn.SiLU(),
158
- conv_nd(dims, 16, 16, 3, padding=1),
159
- nn.SiLU(),
160
- conv_nd(dims, 16, 32, 3, padding=1, stride=2),
161
- nn.SiLU(),
162
- conv_nd(dims, 32, 32, 3, padding=1),
163
- nn.SiLU(),
164
- conv_nd(dims, 32, 96, 3, padding=1, stride=2),
165
- nn.SiLU(),
166
- conv_nd(dims, 96, 96, 3, padding=1),
167
- nn.SiLU(),
168
- conv_nd(dims, 96, 256, 3, padding=1, stride=2),
169
- nn.SiLU(),
170
- zero_module(conv_nd(dims, 256, model_channels, 3, padding=1))
171
- )
172
-
173
- self._feature_size = model_channels
174
- input_block_chans = [model_channels]
175
- ch = model_channels
176
- ds = 1
177
- for level, mult in enumerate(channel_mult):
178
- for nr in range(self.num_res_blocks[level]):
179
- layers = [
180
- ResBlock(
181
- ch,
182
- time_embed_dim,
183
- dropout,
184
- out_channels=mult * model_channels,
185
- dims=dims,
186
- use_checkpoint=use_checkpoint,
187
- use_scale_shift_norm=use_scale_shift_norm,
188
- )
189
- ]
190
- ch = mult * model_channels
191
- if ds in attention_resolutions:
192
- if num_head_channels == -1:
193
- dim_head = ch // num_heads
194
- else:
195
- num_heads = ch // num_head_channels
196
- dim_head = num_head_channels
197
- if legacy:
198
- # num_heads = 1
199
- dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
200
- if exists(disable_self_attentions):
201
- disabled_sa = disable_self_attentions[level]
202
- else:
203
- disabled_sa = False
204
-
205
- if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
206
- layers.append(
207
- AttentionBlock(
208
- ch,
209
- use_checkpoint=use_checkpoint,
210
- num_heads=num_heads,
211
- num_head_channels=dim_head,
212
- use_new_attention_order=use_new_attention_order,
213
- ) if not use_spatial_transformer else SpatialTransformer(
214
- ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
215
- disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
216
- use_checkpoint=use_checkpoint
217
- )
218
- )
219
- self.input_blocks.append(TimestepEmbedSequential(*layers))
220
- self.zero_convs.append(self.make_zero_conv(ch))
221
- self._feature_size += ch
222
- input_block_chans.append(ch)
223
- if level != len(channel_mult) - 1:
224
- out_ch = ch
225
- self.input_blocks.append(
226
- TimestepEmbedSequential(
227
- ResBlock(
228
- ch,
229
- time_embed_dim,
230
- dropout,
231
- out_channels=out_ch,
232
- dims=dims,
233
- use_checkpoint=use_checkpoint,
234
- use_scale_shift_norm=use_scale_shift_norm,
235
- down=True,
236
- )
237
- if resblock_updown
238
- else Downsample(
239
- ch, conv_resample, dims=dims, out_channels=out_ch
240
- )
241
- )
242
- )
243
- ch = out_ch
244
- input_block_chans.append(ch)
245
- self.zero_convs.append(self.make_zero_conv(ch))
246
- ds *= 2
247
- self._feature_size += ch
248
-
249
- if num_head_channels == -1:
250
- dim_head = ch // num_heads
251
- else:
252
- num_heads = ch // num_head_channels
253
- dim_head = num_head_channels
254
- if legacy:
255
- # num_heads = 1
256
- dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
257
- self.middle_block = TimestepEmbedSequential(
258
- ResBlock(
259
- ch,
260
- time_embed_dim,
261
- dropout,
262
- dims=dims,
263
- use_checkpoint=use_checkpoint,
264
- use_scale_shift_norm=use_scale_shift_norm,
265
- ),
266
- AttentionBlock(
267
- ch,
268
- use_checkpoint=use_checkpoint,
269
- num_heads=num_heads,
270
- num_head_channels=dim_head,
271
- use_new_attention_order=use_new_attention_order,
272
- ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
273
- ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
274
- disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
275
- use_checkpoint=use_checkpoint
276
- ),
277
- ResBlock(
278
- ch,
279
- time_embed_dim,
280
- dropout,
281
- dims=dims,
282
- use_checkpoint=use_checkpoint,
283
- use_scale_shift_norm=use_scale_shift_norm,
284
- ),
285
- )
286
- self.middle_block_out = self.make_zero_conv(ch)
287
- self._feature_size += ch
288
-
289
- def make_zero_conv(self, channels):
290
- return TimestepEmbedSequential(zero_module(conv_nd(self.dims, channels, channels, 1, padding=0)))
291
-
292
- def forward(self, x, hint, timesteps, context, **kwargs):
293
- # print("cldm",hint.shape,x.shape)
294
- t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
295
- emb = self.time_embed(t_emb)
296
-
297
- guided_hint = self.input_hint_block(hint, emb, context)
298
-
299
- outs = []
300
-
301
- h = x.type(self.dtype)
302
- # h_in=h
303
-
304
- for module, zero_conv in zip(self.input_blocks, self.zero_convs):
305
- if guided_hint is not None:
306
- h = module(h, emb, context)#,dcn_guide=h_in)
307
- h += guided_hint
308
- guided_hint = None
309
- else:
310
- # print("dcn_guide")
311
- h = module(h, emb, context)#,dcn_guide=h_in)
312
- outs.append(zero_conv(h, emb, context))
313
-
314
- h = self.middle_block(h, emb, context)#,dcn_guide=h_in)
315
- outs.append(self.middle_block_out(h, emb, context))
316
-
317
- return outs
318
-
319
-
320
- class ControlLDM(LatentDiffusion):
321
-
322
- def __init__(self, control_stage_config, control_key, only_mid_control, *args, **kwargs): #freeze
323
- # print(control_stage_config)
324
- super().__init__(*args, **kwargs)
325
- self.control_model = instantiate_from_config(control_stage_config)
326
- self.control_key = control_key
327
- self.only_mid_control = only_mid_control
328
- self.control_scales = [1.0] * 13
329
- # if freeze==True:
330
- # self.freeze()
331
-
332
- # def freeze(self):
333
- # #self.train = disabled_train
334
- # for param in self.parameters():
335
- # param.requires_grad = False
336
-
337
-
338
-
339
- @torch.no_grad()
340
- def get_input(self, batch, k, bs=None, *args, **kwargs):
341
- x,mask,masked_image_latents, c = super().get_input(batch, self.first_stage_key, *args, **kwargs)
342
- control = batch[self.control_key]
343
- if bs is not None:
344
- control = control[:bs]
345
- control = control.to(self.device)
346
- control = einops.rearrange(control, 'b h w c -> b c h w')
347
- control = control.to(memory_format=torch.contiguous_format).float()
348
- return x,mask,masked_image_latents, dict(c_crossattn=[c], c_concat=[control])
349
-
350
- def apply_model(self, x_noisy,mask,masked_image_latents, t, cond, *args, **kwargs):
351
- assert isinstance(cond, dict)
352
- diffusion_model = self.model.diffusion_model
353
-
354
- cond_txt = torch.cat(cond['c_crossattn'], 1)
355
- # print(cond_txt.shape,cond['c_crossattn'].shape)
356
- if cond['c_concat'] is None:
357
- eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=None, only_mid_control=self.only_mid_control)
358
- else:
359
- control = self.control_model(x=x_noisy, hint=torch.cat(cond['c_concat'], 1), timesteps=t, context=cond_txt)
360
- control = [c * scale for c, scale in zip(control, self.control_scales)]
361
- mask=torch.cat([mask] * x_noisy.shape[0])
362
- masked_image_latents=torch.cat([masked_image_latents] * x_noisy.shape[0])
363
- x_noisy = torch.cat([x_noisy,mask,masked_image_latents], dim=1)
364
- eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=control, only_mid_control=self.only_mid_control)
365
-
366
- return eps
367
-
368
- def apply_model_addhint(self, x_noisy,mask,masked_image_latents, t, cond, *args, **kwargs):
369
- assert isinstance(cond, dict)
370
- diffusion_model = self.model.diffusion_model
371
-
372
- cond_txt = torch.cat(cond['c_crossattn'], 1)
373
- # print(cond_txt.shape,cond['c_crossattn'].shape)
374
- if cond['c_concat'] is None:
375
- eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=None, only_mid_control=self.only_mid_control)
376
- else:
377
- control = self.control_model(x=x_noisy, hint=torch.cat(cond['c_concat'], 1), timesteps=t, context=cond_txt)
378
- control = [c * scale for c, scale in zip(control, self.control_scales)]
379
- # print(x_noisy.shape,mask.shape,masked_image_latents.shape)
380
- x_noisy = torch.cat([x_noisy,mask,masked_image_latents], dim=1)
381
- eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=control, only_mid_control=self.only_mid_control)
382
-
383
- return eps
384
-
385
- @torch.no_grad()
386
- def get_unconditional_conditioning(self, N):
387
- return self.get_learned_conditioning([""] * N)
388
- # def get_unconditional_conditioning(self, N,hint_image):
389
- # hint_image[:,:,:,:]=0
390
- # return self.get_learned_conditioning(([""] * N,hint_image))
391
-
392
- # @torch.no_grad()
393
- # def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None,
394
- # quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
395
- # plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None,
396
- # use_ema_scope=True,
397
- # **kwargs):
398
- # use_ddim = ddim_steps is not None
399
-
400
- # log = dict()
401
- # z,mask,masked_image_latents, c = self.get_input(batch, self.first_stage_key, bs=N)
402
- # c_cat, c = c["c_concat"][0][:N], c["c_crossattn"][0][:N]
403
- # N = min(z.shape[0], N)
404
- # n_row = min(z.shape[0], n_row)
405
- # log["reconstruction"] = self.decode_first_stage(z)
406
- # log["control"] = c_cat * 2.0 - 1.0
407
- # log["conditioning"] = log_txt_as_img((512, 512), batch[self.cond_stage_key], size=16)
408
- # txt,hint_image=batch[self.cond_stage_key]
409
- # if plot_diffusion_rows:
410
- # # get diffusion row
411
- # diffusion_row = list()
412
- # z_start = z[:n_row]
413
- # for t in range(self.num_timesteps):
414
- # if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
415
- # t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
416
- # t = t.to(self.device).long()
417
- # noise = torch.randn_like(z_start)
418
- # z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
419
- # diffusion_row.append(self.decode_first_stage(z_noisy))
420
-
421
- # diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
422
- # diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
423
- # diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
424
- # diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
425
- # log["diffusion_row"] = diffusion_grid
426
-
427
- # if sample:
428
- # # get denoise row
429
- # samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
430
- # batch_size=N, ddim=use_ddim,
431
- # ddim_steps=ddim_steps, eta=ddim_eta)
432
- # x_samples = self.decode_first_stage(samples)
433
- # log["samples"] = x_samples
434
- # if plot_denoise_rows:
435
- # denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
436
- # log["denoise_row"] = denoise_grid
437
-
438
- # if unconditional_guidance_scale > 1.0:
439
- # uc_cross = self.get_unconditional_conditioning(N,hint_image)
440
- # uc_cat = c_cat # torch.zeros_like(c_cat)
441
- # uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]}
442
- # samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
443
- # batch_size=N, ddim=use_ddim,
444
- # ddim_steps=ddim_steps, eta=ddim_eta,
445
- # unconditional_guidance_scale=unconditional_guidance_scale,
446
- # unconditional_conditioning=uc_full,
447
- # )
448
- # x_samples_cfg = self.decode_first_stage(samples_cfg)
449
- # log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
450
-
451
- # return log
452
-
453
- @torch.no_grad()
454
- def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None,
455
- quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
456
- plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None,
457
- use_ema_scope=True,
458
- **kwargs):
459
- use_ddim = ddim_steps is not None
460
-
461
- log = dict()
462
- z,mask,masked_image_latents, c = self.get_input(batch, self.first_stage_key, bs=N, )
463
- c_cat, c = c["c_concat"][0][:N], c["c_crossattn"][0][:N]
464
- N = min(z.shape[0], N)
465
- n_row = min(z.shape[0], n_row)
466
- log["reconstruction"] = self.decode_first_stage(z)
467
- log["control"] = c_cat * 2.0 - 1.0
468
- log["conditioning"] = log_txt_as_img((512, 512),batch[self.masked_image], batch[self.cond_stage_key], size=16)
469
-
470
- if plot_diffusion_rows:
471
- # get diffusion row
472
- diffusion_row = list()
473
- z_start = z[:n_row]
474
- for t in range(self.num_timesteps):
475
- if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
476
- t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
477
- t = t.to(self.device).long()
478
- noise = torch.randn_like(z_start)
479
- z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
480
- diffusion_row.append(self.decode_first_stage(z_noisy))
481
-
482
- diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
483
- diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
484
- diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
485
- diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
486
- log["diffusion_row"] = diffusion_grid
487
-
488
- if sample:
489
- # get denoise row
490
- samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},mask=mask,masked_image_latents=masked_image_latents,
491
- batch_size=N, ddim=use_ddim,
492
- ddim_steps=ddim_steps, eta=ddim_eta)
493
- x_samples = self.decode_first_stage(samples)
494
- log["samples"] = x_samples
495
- if plot_denoise_rows:
496
- denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
497
- log["denoise_row"] = denoise_grid
498
-
499
- if unconditional_guidance_scale > 1.0:
500
- uc_cross = self.get_unconditional_conditioning(N)
501
- uc_cat = c_cat # torch.zeros_like(c_cat)
502
- uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]}
503
- samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},mask=mask,masked_image_latents=masked_image_latents,
504
- batch_size=N, ddim=use_ddim,
505
- ddim_steps=ddim_steps, eta=ddim_eta,
506
- unconditional_guidance_scale=unconditional_guidance_scale,
507
- unconditional_conditioning=uc_full,
508
- )
509
- x_samples_cfg = self.decode_first_stage(samples_cfg)
510
- log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
511
-
512
- return log
513
- @torch.no_grad()
514
- def sample_log(self, cond,mask,masked_image_latents, batch_size, ddim, ddim_steps, **kwargs):
515
- ddim_sampler = DDIMSampler(self)
516
- b, c, h, w = cond["c_concat"][0].shape
517
- shape = (self.channels, h // 8, w // 8)
518
- samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond,mask=mask,masked_image_latents=masked_image_latents, verbose=False, **kwargs)
519
- return samples, intermediates
520
-
521
- def configure_optimizers(self):
522
- lr = self.learning_rate
523
- params = list(self.control_model.parameters())
524
- # head_params=list()
525
- # for name,param in self.control_model.named_parameters(): #self.model.named_parameters():
526
- # if "dcn" in name:
527
- # # print(name)
528
- # head_params.append(param)
529
- # # params = list(self.control_model.parameters())+head_params
530
- # params = head_params
531
- if not self.sd_locked:
532
- params += list(self.model.diffusion_model.output_blocks.parameters())
533
- params += list(self.model.diffusion_model.out.parameters())
534
- opt = torch.optim.AdamW(params, lr=lr)
535
- return opt
536
-
537
- def low_vram_shift(self, is_diffusing):
538
- if is_diffusing:
539
- self.model = self.model.cuda()
540
- self.control_model = self.control_model.cuda()
541
- self.first_stage_model = self.first_stage_model.cpu()
542
- self.cond_stage_model = self.cond_stage_model.cpu()
543
- else:
544
- self.model = self.model.cpu()
545
- self.control_model = self.control_model.cpu()
546
- self.first_stage_model = self.first_stage_model.cuda()
547
- self.cond_stage_model = self.cond_stage_model.cuda()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/cldm/ddim_haced_sag_step.py DELETED
@@ -1,494 +0,0 @@
1
- """SAMPLING ONLY."""
2
-
3
- import torch
4
- import numpy as np
5
- from tqdm import tqdm
6
-
7
- from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
8
- import torch.nn.functional as F
9
-
10
- import cv2
11
-
12
- import einops
13
- # Gaussian blur
14
- def gaussian_blur_2d(img, kernel_size, sigma):
15
- ksize_half = (kernel_size - 1) * 0.5
16
-
17
- x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size)
18
-
19
- pdf = torch.exp(-0.5 * (x / sigma).pow(2))
20
-
21
- x_kernel = pdf / pdf.sum()
22
- x_kernel = x_kernel.to(device=img.device, dtype=img.dtype)
23
-
24
- kernel2d = torch.mm(x_kernel[:, None], x_kernel[None, :])
25
- kernel2d = kernel2d.expand(img.shape[-3], 1, kernel2d.shape[0], kernel2d.shape[1])
26
-
27
- padding = [kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2]
28
-
29
- img = F.pad(img, padding, mode="reflect")
30
- img = F.conv2d(img, kernel2d, groups=img.shape[-3])
31
-
32
- return img
33
-
34
- # processes and stores attention probabilities
35
- class CrossAttnStoreProcessor:
36
- def __init__(self):
37
- self.attention_probs = None
38
-
39
- def __call__(
40
- self,
41
- attn,
42
- hidden_states,
43
- encoder_hidden_states=None,
44
- attention_mask=None,
45
- ):
46
- batch_size, sequence_length, _ = hidden_states.shape
47
- attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
48
- query = attn.to_q(hidden_states)
49
-
50
- if encoder_hidden_states is None:
51
- encoder_hidden_states = hidden_states
52
- elif attn.norm_cross:
53
- encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
54
-
55
- key = attn.to_k(encoder_hidden_states)
56
- value = attn.to_v(encoder_hidden_states)
57
-
58
- query = attn.head_to_batch_dim(query)
59
- key = attn.head_to_batch_dim(key)
60
- value = attn.head_to_batch_dim(value)
61
-
62
- self.attention_probs = attn.get_attention_scores(query, key, attention_mask)
63
- hidden_states = torch.bmm(self.attention_probs, value)
64
- hidden_states = attn.batch_to_head_dim(hidden_states)
65
-
66
- # linear proj
67
- hidden_states = attn.to_out[0](hidden_states)
68
- # dropout
69
- hidden_states = attn.to_out[1](hidden_states)
70
-
71
- return hidden_states
72
-
73
- class DDIMSampler(object):
74
- def __init__(self, model, schedule="linear", **kwargs):
75
- super().__init__()
76
- self.model = model
77
- self.ddpm_num_timesteps = model.num_timesteps
78
- self.schedule = schedule
79
-
80
- def register_buffer(self, name, attr):
81
- if type(attr) == torch.Tensor:
82
- if attr.device != torch.device("cuda"):
83
- attr = attr.to(torch.device("cuda"))
84
- setattr(self, name, attr)
85
-
86
- def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
87
- self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
88
- num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
89
- alphas_cumprod = self.model.alphas_cumprod
90
- assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
91
- to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
92
-
93
- self.register_buffer('betas', to_torch(self.model.betas))
94
- self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
95
- self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
96
-
97
- # calculations for diffusion q(x_t | x_{t-1}) and others
98
- self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
99
- self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
100
- self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
101
- self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
102
- self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
103
-
104
- # ddim sampling parameters
105
- ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
106
- ddim_timesteps=self.ddim_timesteps,
107
- eta=ddim_eta,verbose=verbose)
108
- self.register_buffer('ddim_sigmas', ddim_sigmas)
109
- self.register_buffer('ddim_alphas', ddim_alphas)
110
- self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
111
- self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
112
- sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
113
- (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
114
- 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
115
- self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
116
-
117
- @torch.no_grad()
118
- def sample(self,
119
- model,
120
- S,
121
- batch_size,
122
- shape,
123
- conditioning=None,
124
- callback=None,
125
- normals_sequence=None,
126
- img_callback=None,
127
- quantize_x0=False,
128
- eta=0.,
129
- mask=None,
130
- masked_image_latents=None,
131
- x0=None,
132
- temperature=1.,
133
- noise_dropout=0.,
134
- score_corrector=None,
135
- corrector_kwargs=None,
136
- verbose=True,
137
- x_T=None,
138
- log_every_t=100,
139
- unconditional_guidance_scale=1.,
140
- sag_scale=0.75,
141
- SAG_influence_step=600,
142
- noise = None,
143
- unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
144
- dynamic_threshold=None,
145
- ucg_schedule=None,
146
- **kwargs
147
- ):
148
- if conditioning is not None:
149
- if isinstance(conditioning, dict):
150
- ctmp = conditioning[list(conditioning.keys())[0]]
151
- while isinstance(ctmp, list): ctmp = ctmp[0]
152
- cbs = ctmp.shape[0]
153
- if cbs != batch_size:
154
- print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
155
-
156
- elif isinstance(conditioning, list):
157
- for ctmp in conditioning:
158
- if ctmp.shape[0] != batch_size:
159
- print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
160
-
161
- else:
162
- if conditioning.shape[0] != batch_size:
163
- print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
164
-
165
- self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
166
- # sampling
167
- # print(shape)
168
- C, H, W = shape
169
- size = (batch_size, C, H, W)
170
- print(f'Data shape for DDIM sampling is {size}, eta {eta}')
171
-
172
- samples, intermediates = self.ddim_sampling(model,conditioning, size,
173
- callback=callback,
174
- img_callback=img_callback,
175
- quantize_denoised=quantize_x0,
176
- mask=mask,masked_image_latents=masked_image_latents, x0=x0,
177
- ddim_use_original_steps=False,
178
- noise_dropout=noise_dropout,
179
- temperature=temperature,
180
- score_corrector=score_corrector,
181
- corrector_kwargs=corrector_kwargs,
182
- x_T=x_T,
183
- log_every_t=log_every_t,
184
- unconditional_guidance_scale=unconditional_guidance_scale,
185
- sag_scale = sag_scale,
186
- SAG_influence_step = SAG_influence_step,
187
- noise = noise,
188
- unconditional_conditioning=unconditional_conditioning,
189
- dynamic_threshold=dynamic_threshold,
190
- ucg_schedule=ucg_schedule
191
- )
192
- return samples, intermediates
193
-
194
- def add_noise(self,
195
- original_samples: torch.FloatTensor,
196
- noise: torch.FloatTensor,
197
- timesteps: torch.IntTensor,
198
- ) -> torch.FloatTensor:
199
- betas = torch.linspace(0.00085, 0.0120, 1000, dtype=torch.float32)
200
- alphas = 1.0 - betas
201
- alphas_cumprod = torch.cumprod(alphas, dim=0)
202
- alphas_cumprod = alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
203
- timesteps = timesteps.to(original_samples.device)
204
-
205
- sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
206
- sqrt_alpha_prod = sqrt_alpha_prod.flatten()
207
- while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
208
- sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
209
-
210
- sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
211
- sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
212
- while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
213
- sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
214
-
215
- noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
216
-
217
- return noisy_samples
218
-
219
-
220
- def sag_masking(self, original_latents,model_output,x, attn_map, map_size, t, eps):
221
- # Same masking process as in SAG paper: https://arxiv.org/pdf/2210.00939.pdf
222
- bh, hw1, hw2 = attn_map.shape
223
- b, latent_channel, latent_h, latent_w = original_latents.shape
224
- h = 4 #self.unet.config.attention_head_dim
225
- if isinstance(h, list):
226
- h = h[-1]
227
- attn_map = attn_map.reshape(b, h, hw1, hw2)
228
- attn_mask = attn_map.mean(1, keepdim=False).sum(1, keepdim=False) > 1.0
229
- attn_mask = (
230
- attn_mask.reshape(b, map_size[0], map_size[1])
231
- .unsqueeze(1)
232
- .repeat(1, latent_channel, 1, 1)
233
- .type(attn_map.dtype)
234
- )
235
- attn_mask = F.interpolate(attn_mask, (latent_h, latent_w))
236
- degraded_latents = gaussian_blur_2d(original_latents, kernel_size=9, sigma=1.0)
237
- degraded_latents = degraded_latents * attn_mask + original_latents * (1 - attn_mask) #x#original_latents
238
-
239
- return degraded_latents
240
-
241
- def pred_epsilon(self, sample, model_output, timestep):
242
- alpha_prod_t = timestep
243
-
244
- beta_prod_t = 1 - alpha_prod_t
245
- # print(self.model.parameterization)#eps
246
- if self.model.parameterization == "eps":
247
- pred_eps = model_output
248
- elif self.model.parameterization == "sample":
249
- pred_eps = (sample - (alpha_prod_t**0.5) * model_output) / (beta_prod_t**0.5)
250
- elif self.model.parameterization == "v":
251
- pred_eps = (beta_prod_t**0.5) * sample + (alpha_prod_t**0.5) * model_output
252
- else:
253
- raise ValueError(
254
- f"prediction_type given as {self.scheduler.config.prediction_type} must be one of `eps`, `sample`,"
255
- " or `v`"
256
- )
257
-
258
- return pred_eps
259
-
260
- @torch.no_grad()
261
- def ddim_sampling(self,model, cond, shape,
262
- x_T=None, ddim_use_original_steps=False,
263
- callback=None, timesteps=None, quantize_denoised=False,
264
- mask=None,masked_image_latents=None, x0=None, img_callback=None, log_every_t=100,
265
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
266
- unconditional_guidance_scale=1.,sag_scale = 0.75, SAG_influence_step=600, sag_enable = True, noise = None, unconditional_conditioning=None, dynamic_threshold=None,
267
- ucg_schedule=None):
268
- device = self.model.betas.device
269
- b = shape[0]
270
- if x_T is None:
271
- img = torch.randn(shape, device=device)
272
- else:
273
- img = x_T
274
- # timesteps =100
275
- if timesteps is None:
276
- timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
277
- elif timesteps is not None and not ddim_use_original_steps:
278
- subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
279
- timesteps = self.ddim_timesteps[:subset_end]
280
- # timesteps=timesteps[:-3]
281
- # print("timesteps",timesteps)
282
- intermediates = {'x_inter': [img], 'pred_x0': [img]}
283
- time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
284
- total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
285
- print(f"Running DDIM Sampling with {total_steps} timesteps")
286
-
287
- iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
288
-
289
- for i, step in enumerate(iterator):
290
- # print(step)
291
- if step > SAG_influence_step:
292
- sag_enable_t=True
293
- else:
294
- sag_enable_t=False
295
- index = total_steps - i - 1
296
- ts = torch.full((b,), step, device=device, dtype=torch.long)
297
-
298
- if ucg_schedule is not None:
299
- assert len(ucg_schedule) == len(time_range)
300
- unconditional_guidance_scale = ucg_schedule[i]
301
-
302
- outs = self.p_sample_ddim(img,mask,masked_image_latents, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
303
- quantize_denoised=quantize_denoised, temperature=temperature,
304
- noise_dropout=noise_dropout, score_corrector=score_corrector,
305
- corrector_kwargs=corrector_kwargs,
306
- unconditional_guidance_scale=unconditional_guidance_scale,
307
- sag_scale = sag_scale,
308
- sag_enable=sag_enable_t,
309
- noise =noise,
310
- unconditional_conditioning=unconditional_conditioning,
311
- dynamic_threshold=dynamic_threshold)
312
- img, pred_x0 = outs
313
- if callback: callback(i)
314
- if img_callback: img_callback(pred_x0, i)
315
-
316
- if index % log_every_t == 0 or index == total_steps - 1:
317
- intermediates['x_inter'].append(img)
318
- intermediates['pred_x0'].append(pred_x0)
319
- x_samples = model.decode_first_stage(img)
320
- x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
321
-
322
- #single image replace L channel
323
- results_ori = [x_samples[i] for i in range(1)]
324
- # results_ori=[i for i in results_ori]
325
-
326
- # cv2.imwrite("result_ori"+str(step)+".png",cv2.cvtColor(results_ori[0],cv2.COLOR_RGB2BGR))
327
- return img, intermediates
328
-
329
- @torch.no_grad()
330
- def p_sample_ddim(self, x,mask,masked_image_latents, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
331
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
332
- unconditional_guidance_scale=1.,sag_scale = 0.75, sag_enable=True, noise=None, unconditional_conditioning=None,
333
- dynamic_threshold=None):
334
- b, *_, device = *x.shape, x.device
335
-
336
- if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
337
- model_output = self.model.apply_model(x,mask,masked_image_latents, t, c)
338
- else:
339
- model_t = self.model.apply_model(x,mask,masked_image_latents, t, c)
340
- model_uncond = self.model.apply_model(x,mask,masked_image_latents, t, unconditional_conditioning)
341
- model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
342
-
343
- if self.model.parameterization == "v":
344
- e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
345
- else:
346
- e_t = model_output
347
-
348
- if score_corrector is not None:
349
- assert self.model.parameterization == "eps", 'not implemented'
350
- e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
351
-
352
- alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
353
- alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
354
- sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
355
- sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
356
- # select parameters corresponding to the currently considered timestep
357
- a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
358
- a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
359
- sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
360
- sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
361
-
362
- # current prediction for x_0
363
- if self.model.parameterization != "v":
364
- pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
365
- else:
366
- pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
367
-
368
- if quantize_denoised:
369
- pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
370
-
371
- if dynamic_threshold is not None:
372
- raise NotImplementedError()
373
- if sag_enable == True:
374
- uncond_attn, cond_attn = self.model.model.diffusion_model.middle_block[1].transformer_blocks[0].attn1.attention_probs.chunk(2)
375
- # self-attention-based degrading of latents
376
- map_size = self.model.model.diffusion_model.middle_block[1].map_size
377
- degraded_latents = self.sag_masking(
378
- pred_x0,model_output,x,uncond_attn, map_size, t, eps = noise, #self.pred_epsilon(x, model_uncond, self.model.alphas_cumprod[t]),#noise
379
- )
380
- if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
381
- degraded_model_output = self.model.apply_model(degraded_latents,mask,masked_image_latents, t, c)
382
- else:
383
- degraded_model_t = self.model.apply_model(degraded_latents,mask,masked_image_latents, t, c)
384
- degraded_model_uncond = self.model.apply_model(degraded_latents,mask,masked_image_latents, t, unconditional_conditioning)
385
- degraded_model_output = degraded_model_uncond + unconditional_guidance_scale * (degraded_model_t - degraded_model_uncond)
386
- # print("sag_scale",sag_scale)
387
- model_output += sag_scale * (model_output - degraded_model_output)
388
- # model_output = (1-sag_scale) * model_output + sag_scale * degraded_model_output
389
-
390
- # current prediction for x_0
391
- if self.model.parameterization != "v":
392
- pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
393
- else:
394
- pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
395
-
396
- if quantize_denoised:
397
- pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
398
-
399
- if dynamic_threshold is not None:
400
- raise NotImplementedError()
401
-
402
- # direction pointing to x_t
403
- dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
404
- noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
405
- if noise_dropout > 0.:
406
- noise = torch.nn.functional.dropout(noise, p=noise_dropout)
407
- x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
408
- return x_prev, pred_x0
409
-
410
- @torch.no_grad()
411
- def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
412
- unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
413
- timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
414
- num_reference_steps = timesteps.shape[0]
415
-
416
- assert t_enc <= num_reference_steps
417
- num_steps = t_enc
418
-
419
- if use_original_steps:
420
- alphas_next = self.alphas_cumprod[:num_steps]
421
- alphas = self.alphas_cumprod_prev[:num_steps]
422
- else:
423
- alphas_next = self.ddim_alphas[:num_steps]
424
- alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
425
-
426
- x_next = x0
427
- intermediates = []
428
- inter_steps = []
429
- for i in tqdm(range(num_steps), desc='Encoding Image'):
430
- t = torch.full((x0.shape[0],), timesteps[i], device=self.model.device, dtype=torch.long)
431
- if unconditional_guidance_scale == 1.:
432
- noise_pred = self.model.apply_model(x_next, t, c)
433
- else:
434
- assert unconditional_conditioning is not None
435
- e_t_uncond, noise_pred = torch.chunk(
436
- self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
437
- torch.cat((unconditional_conditioning, c))), 2)
438
- noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
439
-
440
- xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
441
- weighted_noise_pred = alphas_next[i].sqrt() * (
442
- (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
443
- x_next = xt_weighted + weighted_noise_pred
444
- if return_intermediates and i % (
445
- num_steps // return_intermediates) == 0 and i < num_steps - 1:
446
- intermediates.append(x_next)
447
- inter_steps.append(i)
448
- elif return_intermediates and i >= num_steps - 2:
449
- intermediates.append(x_next)
450
- inter_steps.append(i)
451
- if callback: callback(i)
452
-
453
- out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
454
- if return_intermediates:
455
- out.update({'intermediates': intermediates})
456
- return x_next, out
457
-
458
- @torch.no_grad()
459
- def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
460
- # fast, but does not allow for exact reconstruction
461
- # t serves as an index to gather the correct alphas
462
- if use_original_steps:
463
- sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
464
- sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
465
- else:
466
- sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
467
- sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
468
-
469
- if noise is None:
470
- noise = torch.randn_like(x0)
471
- return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
472
- extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
473
-
474
- @torch.no_grad()
475
- def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
476
- use_original_steps=False, callback=None):
477
-
478
- timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
479
- timesteps = timesteps[:t_start]
480
-
481
- time_range = np.flip(timesteps)
482
- total_steps = timesteps.shape[0]
483
- print(f"Running DDIM Sampling with {total_steps} timesteps")
484
-
485
- iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
486
- x_dec = x_latent
487
- for i, step in enumerate(iterator):
488
- index = total_steps - i - 1
489
- ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
490
- x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
491
- unconditional_guidance_scale=unconditional_guidance_scale,
492
- unconditional_conditioning=unconditional_conditioning)
493
- if callback: callback(i)
494
- return x_dec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/cldm/ddim_hacked_sag.py DELETED
@@ -1,543 +0,0 @@
1
- """SAMPLING ONLY."""
2
-
3
- import torch
4
- import numpy as np
5
- from tqdm import tqdm
6
-
7
- from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
8
- import torch.nn.functional as F
9
-
10
- import cv2
11
- # Gaussian blur
12
- def gaussian_blur_2d(img, kernel_size, sigma):
13
- ksize_half = (kernel_size - 1) * 0.5
14
-
15
- x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size)
16
-
17
- pdf = torch.exp(-0.5 * (x / sigma).pow(2))
18
-
19
- x_kernel = pdf / pdf.sum()
20
- x_kernel = x_kernel.to(device=img.device, dtype=img.dtype)
21
-
22
- kernel2d = torch.mm(x_kernel[:, None], x_kernel[None, :])
23
- kernel2d = kernel2d.expand(img.shape[-3], 1, kernel2d.shape[0], kernel2d.shape[1])
24
-
25
- padding = [kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2]
26
-
27
- img = F.pad(img, padding, mode="reflect")
28
- img = F.conv2d(img, kernel2d, groups=img.shape[-3])
29
-
30
- return img
31
-
32
- # processes and stores attention probabilities
33
- class CrossAttnStoreProcessor:
34
- def __init__(self):
35
- self.attention_probs = None
36
-
37
- def __call__(
38
- self,
39
- attn,
40
- hidden_states,
41
- encoder_hidden_states=None,
42
- attention_mask=None,
43
- ):
44
- batch_size, sequence_length, _ = hidden_states.shape
45
- attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
46
- query = attn.to_q(hidden_states)
47
-
48
- if encoder_hidden_states is None:
49
- encoder_hidden_states = hidden_states
50
- elif attn.norm_cross:
51
- encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
52
-
53
- key = attn.to_k(encoder_hidden_states)
54
- value = attn.to_v(encoder_hidden_states)
55
-
56
- query = attn.head_to_batch_dim(query)
57
- key = attn.head_to_batch_dim(key)
58
- value = attn.head_to_batch_dim(value)
59
-
60
- self.attention_probs = attn.get_attention_scores(query, key, attention_mask)
61
- hidden_states = torch.bmm(self.attention_probs, value)
62
- hidden_states = attn.batch_to_head_dim(hidden_states)
63
-
64
- # linear proj
65
- hidden_states = attn.to_out[0](hidden_states)
66
- # dropout
67
- hidden_states = attn.to_out[1](hidden_states)
68
-
69
- return hidden_states
70
-
71
- class DDIMSampler(object):
72
- def __init__(self, model, schedule="linear", **kwargs):
73
- super().__init__()
74
- self.model = model
75
- self.ddpm_num_timesteps = model.num_timesteps
76
- self.schedule = schedule
77
-
78
- def register_buffer(self, name, attr):
79
- if type(attr) == torch.Tensor:
80
- if attr.device != torch.device("cuda"):
81
- attr = attr.to(torch.device("cuda"))
82
- setattr(self, name, attr)
83
-
84
- def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
85
- self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
86
- num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
87
- alphas_cumprod = self.model.alphas_cumprod
88
- assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
89
- to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
90
-
91
- self.register_buffer('betas', to_torch(self.model.betas))
92
- self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
93
- self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
94
-
95
- # calculations for diffusion q(x_t | x_{t-1}) and others
96
- self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
97
- self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
98
- self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
99
- self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
100
- self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
101
-
102
- # ddim sampling parameters
103
- ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
104
- ddim_timesteps=self.ddim_timesteps,
105
- eta=ddim_eta,verbose=verbose)
106
- self.register_buffer('ddim_sigmas', ddim_sigmas)
107
- self.register_buffer('ddim_alphas', ddim_alphas)
108
- self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
109
- self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
110
- sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
111
- (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
112
- 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
113
- self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
114
-
115
- @torch.no_grad()
116
- def sample(self,
117
- S,
118
- batch_size,
119
- shape,
120
- conditioning=None,
121
- callback=None,
122
- normals_sequence=None,
123
- img_callback=None,
124
- quantize_x0=False,
125
- eta=0.,
126
- mask=None,
127
- masked_image_latents=None,
128
- x0=None,
129
- temperature=1.,
130
- noise_dropout=0.,
131
- score_corrector=None,
132
- corrector_kwargs=None,
133
- verbose=True,
134
- x_T=None,
135
- log_every_t=100,
136
- unconditional_guidance_scale=1.,
137
- sag_scale=0.75,
138
- SAG_influence_step=600,
139
- noise = None,
140
- unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
141
- dynamic_threshold=None,
142
- ucg_schedule=None,
143
- **kwargs
144
- ):
145
- if conditioning is not None:
146
- if isinstance(conditioning, dict):
147
- ctmp = conditioning[list(conditioning.keys())[0]]
148
- while isinstance(ctmp, list): ctmp = ctmp[0]
149
- cbs = ctmp.shape[0]
150
- if cbs != batch_size:
151
- print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
152
-
153
- elif isinstance(conditioning, list):
154
- for ctmp in conditioning:
155
- if ctmp.shape[0] != batch_size:
156
- print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
157
-
158
- else:
159
- if conditioning.shape[0] != batch_size:
160
- print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
161
-
162
- self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
163
- # sampling
164
- C, H, W = shape
165
- size = (batch_size, C, H, W)
166
- print(f'Data shape for DDIM sampling is {size}, eta {eta}')
167
-
168
- samples, intermediates = self.ddim_sampling(conditioning, size,
169
- callback=callback,
170
- img_callback=img_callback,
171
- quantize_denoised=quantize_x0,
172
- mask=mask,masked_image_latents=masked_image_latents, x0=x0,
173
- ddim_use_original_steps=False,
174
- noise_dropout=noise_dropout,
175
- temperature=temperature,
176
- score_corrector=score_corrector,
177
- corrector_kwargs=corrector_kwargs,
178
- x_T=x_T,
179
- log_every_t=log_every_t,
180
- unconditional_guidance_scale=unconditional_guidance_scale,
181
- sag_scale = sag_scale,
182
- SAG_influence_step = SAG_influence_step,
183
- noise = noise,
184
- unconditional_conditioning=unconditional_conditioning,
185
- dynamic_threshold=dynamic_threshold,
186
- ucg_schedule=ucg_schedule
187
- )
188
- return samples, intermediates
189
-
190
- def add_noise(self,
191
- original_samples: torch.FloatTensor,
192
- noise: torch.FloatTensor,
193
- timesteps: torch.IntTensor,
194
- ) -> torch.FloatTensor:
195
- betas = torch.linspace(0.00085, 0.0120, 1000, dtype=torch.float32)
196
- alphas = 1.0 - betas
197
- alphas_cumprod = torch.cumprod(alphas, dim=0)
198
- alphas_cumprod = alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
199
- timesteps = timesteps.to(original_samples.device)
200
-
201
- sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
202
- sqrt_alpha_prod = sqrt_alpha_prod.flatten()
203
- while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
204
- sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
205
-
206
- sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
207
- sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
208
- while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
209
- sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
210
-
211
- noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
212
-
213
- return noisy_samples
214
- # def add_noise(
215
- # self,
216
- # original_samples: torch.FloatTensor,
217
- # noise: torch.FloatTensor,
218
- # timesteps: torch.FloatTensor,
219
- # sigma_t,
220
- # ) -> torch.FloatTensor:
221
-
222
- # # Make sure sigmas and timesteps have the same device and dtype as original_samples
223
-
224
- # sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype)
225
- # if original_samples.device.type == "mps" and torch.is_floating_point(timesteps):
226
- # # mps does not support float64
227
- # schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32)
228
- # timesteps = timesteps.to(original_samples.device, dtype=torch.float32)
229
- # else:
230
- # schedule_timesteps = self.timesteps.to(original_samples.device)
231
- # timesteps = timesteps.to(original_samples.device)
232
-
233
- # step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
234
-
235
- # sigma = sigmas[step_indices].flatten()
236
- # while len(sigma.shape) < len(original_samples.shape):
237
- # sigma = sigma.unsqueeze(-1)
238
- # # print(sigma_t)
239
- # noisy_samples = original_samples + noise * sigma_t
240
- # return noisy_samples
241
-
242
-
243
- def sag_masking(self, original_latents,model_output,x, attn_map, map_size, t, eps):
244
- # Same masking process as in SAG paper: https://arxiv.org/pdf/2210.00939.pdf
245
- bh, hw1, hw2 = attn_map.shape
246
- b, latent_channel, latent_h, latent_w = original_latents.shape
247
- h = 4 #self.unet.config.attention_head_dim
248
- if isinstance(h, list):
249
- h = h[-1]
250
- # print(attn_map.shape)
251
- # print(original_latents.shape)
252
- # print(map_size)
253
- # Produce attention mask
254
- attn_map = attn_map.reshape(b, h, hw1, hw2)
255
- attn_mask = attn_map.mean(1, keepdim=False).sum(1, keepdim=False) > 1.0
256
- # print(attn_mask.shape)
257
- attn_mask = (
258
- attn_mask.reshape(b, map_size[0], map_size[1])
259
- .unsqueeze(1)
260
- .repeat(1, latent_channel, 1, 1)
261
- .type(attn_map.dtype)
262
- )
263
- attn_mask = F.interpolate(attn_mask, (latent_h, latent_w))
264
- # print(attn_mask.shape)
265
- # cv2.imwrite("attn_mask.png",attn_mask)
266
- # Blur according to the self-attention mask
267
- degraded_latents = gaussian_blur_2d(original_latents, kernel_size=9, sigma=1.0)
268
- # degraded_latents = self.add_noise(degraded_latents, noise=eps, timesteps=t)#,sigma_t=sigma_t)
269
- degraded_latents = degraded_latents * attn_mask + original_latents * (1 - attn_mask) #x#original_latents
270
- # degraded_latents = self.model.get_x_t_from_start_and_t(degraded_latents,t,model_output)
271
- # print(original_latents.shape)
272
- # print(eps.shape)
273
- # Noise it again to match the noise level
274
- # print("t",t)
275
- # degraded_latents = self.add_noise(degraded_latents, noise=eps, timesteps=t)#,sigma_t=sigma_t)
276
-
277
- return degraded_latents
278
-
279
- def pred_epsilon(self, sample, model_output, timestep):
280
- alpha_prod_t = timestep
281
-
282
- beta_prod_t = 1 - alpha_prod_t
283
- # print(self.model.parameterization)#eps
284
- if self.model.parameterization == "eps":
285
- pred_eps = model_output
286
- elif self.model.parameterization == "sample":
287
- pred_eps = (sample - (alpha_prod_t**0.5) * model_output) / (beta_prod_t**0.5)
288
- elif self.model.parameterization == "v":
289
- pred_eps = (beta_prod_t**0.5) * sample + (alpha_prod_t**0.5) * model_output
290
- else:
291
- raise ValueError(
292
- f"prediction_type given as {self.scheduler.config.prediction_type} must be one of `eps`, `sample`,"
293
- " or `v`"
294
- )
295
-
296
- return pred_eps
297
-
298
- @torch.no_grad()
299
- def ddim_sampling(self, cond, shape,
300
- x_T=None, ddim_use_original_steps=False,
301
- callback=None, timesteps=None, quantize_denoised=False,
302
- mask=None,masked_image_latents=None, x0=None, img_callback=None, log_every_t=100,
303
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
304
- unconditional_guidance_scale=1.,sag_scale = 0.75, SAG_influence_step=600, sag_enable = True, noise = None, unconditional_conditioning=None, dynamic_threshold=None,
305
- ucg_schedule=None):
306
- device = self.model.betas.device
307
- b = shape[0]
308
- if x_T is None:
309
- img = torch.randn(shape, device=device)
310
- else:
311
- img = x_T
312
- # timesteps =100
313
- if timesteps is None:
314
- timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
315
- elif timesteps is not None and not ddim_use_original_steps:
316
- subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
317
- timesteps = self.ddim_timesteps[:subset_end]
318
- # timesteps=timesteps[:-3]
319
- # print("timesteps",timesteps)
320
- intermediates = {'x_inter': [img], 'pred_x0': [img]}
321
- time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
322
- total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
323
- print(f"Running DDIM Sampling with {total_steps} timesteps")
324
-
325
- iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
326
-
327
- for i, step in enumerate(iterator):
328
- print(step)
329
- if step > SAG_influence_step:
330
- sag_enable_t=True
331
- else:
332
- sag_enable_t=False
333
- index = total_steps - i - 1
334
- ts = torch.full((b,), step, device=device, dtype=torch.long)
335
-
336
- # if mask is not None:
337
- # assert x0 is not None
338
- # img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
339
- # img = img_orig * mask + (1. - mask) * img
340
-
341
- if ucg_schedule is not None:
342
- assert len(ucg_schedule) == len(time_range)
343
- unconditional_guidance_scale = ucg_schedule[i]
344
-
345
- outs = self.p_sample_ddim(img,mask,masked_image_latents, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
346
- quantize_denoised=quantize_denoised, temperature=temperature,
347
- noise_dropout=noise_dropout, score_corrector=score_corrector,
348
- corrector_kwargs=corrector_kwargs,
349
- unconditional_guidance_scale=unconditional_guidance_scale,
350
- sag_scale = sag_scale,
351
- sag_enable=sag_enable_t,
352
- noise =noise,
353
- unconditional_conditioning=unconditional_conditioning,
354
- dynamic_threshold=dynamic_threshold)
355
- img, pred_x0 = outs
356
- if callback: callback(i)
357
- if img_callback: img_callback(pred_x0, i)
358
-
359
- if index % log_every_t == 0 or index == total_steps - 1:
360
- intermediates['x_inter'].append(img)
361
- intermediates['pred_x0'].append(pred_x0)
362
-
363
- return img, intermediates
364
-
365
- @torch.no_grad()
366
- def p_sample_ddim(self, x,mask,masked_image_latents, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
367
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
368
- unconditional_guidance_scale=1.,sag_scale = 0.75, sag_enable=True, noise=None, unconditional_conditioning=None,
369
- dynamic_threshold=None):
370
- b, *_, device = *x.shape, x.device
371
-
372
- # map_size = None
373
- # def get_map_size(module, input, output):
374
- # nonlocal map_size
375
- # map_size = output.shape[-2:]
376
-
377
- # store_processor = CrossAttnStoreProcessor()
378
- # for name, param in self.model.model.diffusion_model.named_parameters():
379
- # print(name)
380
- # self.model.control_model.middle_block[1].transformer_blocks[0].attn1.processor = store_processor
381
- # print(self.model.model.diffusion_model.middle_block[1].transformer_blocks[0].attn1)
382
- # self.model.model.diffusion_model.middle_block[1].transformer_blocks[0].attn1 = store_processor
383
-
384
- # with self.model.model.diffusion_model.middle_block[1].register_forward_hook(get_map_size):
385
- if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
386
- model_output = self.model.apply_model(x,mask,masked_image_latents, t, c)
387
- else:
388
- model_t = self.model.apply_model(x,mask,masked_image_latents, t, c)
389
- model_uncond = self.model.apply_model(x,mask,masked_image_latents, t, unconditional_conditioning)
390
- model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
391
-
392
- if self.model.parameterization == "v":
393
- e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
394
- else:
395
- e_t = model_output
396
-
397
- if score_corrector is not None:
398
- assert self.model.parameterization == "eps", 'not implemented'
399
- e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
400
-
401
- alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
402
- alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
403
- sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
404
- sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
405
- # select parameters corresponding to the currently considered timestep
406
- a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
407
- a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
408
- sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
409
- sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
410
-
411
- # current prediction for x_0
412
- if self.model.parameterization != "v":
413
- pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
414
- else:
415
- pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
416
-
417
- if quantize_denoised:
418
- pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
419
-
420
- if dynamic_threshold is not None:
421
- raise NotImplementedError()
422
- if sag_enable == True:
423
- uncond_attn, cond_attn = self.model.model.diffusion_model.middle_block[1].transformer_blocks[0].attn1.attention_probs.chunk(2)
424
- # self-attention-based degrading of latents
425
- map_size = self.model.model.diffusion_model.middle_block[1].map_size
426
- degraded_latents = self.sag_masking(
427
- pred_x0,model_output,x,uncond_attn, map_size, t, eps = noise, #self.pred_epsilon(x, model_uncond, self.model.alphas_cumprod[t]),#noise
428
- )
429
- if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
430
- degraded_model_output = self.model.apply_model(degraded_latents,mask,masked_image_latents, t, c)
431
- else:
432
- degraded_model_t = self.model.apply_model(degraded_latents,mask,masked_image_latents, t, c)
433
- degraded_model_uncond = self.model.apply_model(degraded_latents,mask,masked_image_latents, t, unconditional_conditioning)
434
- degraded_model_output = degraded_model_uncond + unconditional_guidance_scale * (degraded_model_t - degraded_model_uncond)
435
- # print("sag_scale",sag_scale)
436
- model_output += sag_scale * (model_output - degraded_model_output)
437
- # model_output = (1-sag_scale) * model_output + sag_scale * degraded_model_output
438
-
439
- # current prediction for x_0
440
- if self.model.parameterization != "v":
441
- pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
442
- else:
443
- pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
444
-
445
- if quantize_denoised:
446
- pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
447
-
448
- if dynamic_threshold is not None:
449
- raise NotImplementedError()
450
-
451
- # direction pointing to x_t
452
- dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
453
- noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
454
- if noise_dropout > 0.:
455
- noise = torch.nn.functional.dropout(noise, p=noise_dropout)
456
- x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
457
- return x_prev, pred_x0
458
-
459
- @torch.no_grad()
460
- def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
461
- unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
462
- timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
463
- num_reference_steps = timesteps.shape[0]
464
-
465
- assert t_enc <= num_reference_steps
466
- num_steps = t_enc
467
-
468
- if use_original_steps:
469
- alphas_next = self.alphas_cumprod[:num_steps]
470
- alphas = self.alphas_cumprod_prev[:num_steps]
471
- else:
472
- alphas_next = self.ddim_alphas[:num_steps]
473
- alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
474
-
475
- x_next = x0
476
- intermediates = []
477
- inter_steps = []
478
- for i in tqdm(range(num_steps), desc='Encoding Image'):
479
- t = torch.full((x0.shape[0],), timesteps[i], device=self.model.device, dtype=torch.long)
480
- if unconditional_guidance_scale == 1.:
481
- noise_pred = self.model.apply_model(x_next, t, c)
482
- else:
483
- assert unconditional_conditioning is not None
484
- e_t_uncond, noise_pred = torch.chunk(
485
- self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
486
- torch.cat((unconditional_conditioning, c))), 2)
487
- noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
488
-
489
- xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
490
- weighted_noise_pred = alphas_next[i].sqrt() * (
491
- (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
492
- x_next = xt_weighted + weighted_noise_pred
493
- if return_intermediates and i % (
494
- num_steps // return_intermediates) == 0 and i < num_steps - 1:
495
- intermediates.append(x_next)
496
- inter_steps.append(i)
497
- elif return_intermediates and i >= num_steps - 2:
498
- intermediates.append(x_next)
499
- inter_steps.append(i)
500
- if callback: callback(i)
501
-
502
- out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
503
- if return_intermediates:
504
- out.update({'intermediates': intermediates})
505
- return x_next, out
506
-
507
- @torch.no_grad()
508
- def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
509
- # fast, but does not allow for exact reconstruction
510
- # t serves as an index to gather the correct alphas
511
- if use_original_steps:
512
- sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
513
- sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
514
- else:
515
- sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
516
- sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
517
-
518
- if noise is None:
519
- noise = torch.randn_like(x0)
520
- return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
521
- extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
522
-
523
- @torch.no_grad()
524
- def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
525
- use_original_steps=False, callback=None):
526
-
527
- timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
528
- timesteps = timesteps[:t_start]
529
-
530
- time_range = np.flip(timesteps)
531
- total_steps = timesteps.shape[0]
532
- print(f"Running DDIM Sampling with {total_steps} timesteps")
533
-
534
- iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
535
- x_dec = x_latent
536
- for i, step in enumerate(iterator):
537
- index = total_steps - i - 1
538
- ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
539
- x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
540
- unconditional_guidance_scale=unconditional_guidance_scale,
541
- unconditional_conditioning=unconditional_conditioning)
542
- if callback: callback(i)
543
- return x_dec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/cldm/hack.py DELETED
@@ -1,111 +0,0 @@
1
- import torch
2
- import einops
3
-
4
- import ldm.modules.encoders.modules
5
- import ldm.modules.attention
6
-
7
- from transformers import logging
8
- from ldm.modules.attention import default
9
-
10
-
11
- def disable_verbosity():
12
- logging.set_verbosity_error()
13
- print('logging improved.')
14
- return
15
-
16
-
17
- def enable_sliced_attention():
18
- ldm.modules.attention.CrossAttention.forward = _hacked_sliced_attentin_forward
19
- print('Enabled sliced_attention.')
20
- return
21
-
22
-
23
- def hack_everything(clip_skip=0):
24
- disable_verbosity()
25
- ldm.modules.encoders.modules.FrozenCLIPEmbedder.forward = _hacked_clip_forward
26
- ldm.modules.encoders.modules.FrozenCLIPEmbedder.clip_skip = clip_skip
27
- print('Enabled clip hacks.')
28
- return
29
-
30
-
31
- # Written by Lvmin
32
- def _hacked_clip_forward(self, text):
33
- PAD = self.tokenizer.pad_token_id
34
- EOS = self.tokenizer.eos_token_id
35
- BOS = self.tokenizer.bos_token_id
36
-
37
- def tokenize(t):
38
- return self.tokenizer(t, truncation=False, add_special_tokens=False)["input_ids"]
39
-
40
- def transformer_encode(t):
41
- if self.clip_skip > 1:
42
- rt = self.transformer(input_ids=t, output_hidden_states=True)
43
- return self.transformer.text_model.final_layer_norm(rt.hidden_states[-self.clip_skip])
44
- else:
45
- return self.transformer(input_ids=t, output_hidden_states=False).last_hidden_state
46
-
47
- def split(x):
48
- return x[75 * 0: 75 * 1], x[75 * 1: 75 * 2], x[75 * 2: 75 * 3]
49
-
50
- def pad(x, p, i):
51
- return x[:i] if len(x) >= i else x + [p] * (i - len(x))
52
-
53
- raw_tokens_list = tokenize(text)
54
- tokens_list = []
55
-
56
- for raw_tokens in raw_tokens_list:
57
- raw_tokens_123 = split(raw_tokens)
58
- raw_tokens_123 = [[BOS] + raw_tokens_i + [EOS] for raw_tokens_i in raw_tokens_123]
59
- raw_tokens_123 = [pad(raw_tokens_i, PAD, 77) for raw_tokens_i in raw_tokens_123]
60
- tokens_list.append(raw_tokens_123)
61
-
62
- tokens_list = torch.IntTensor(tokens_list).to(self.device)
63
-
64
- feed = einops.rearrange(tokens_list, 'b f i -> (b f) i')
65
- y = transformer_encode(feed)
66
- z = einops.rearrange(y, '(b f) i c -> b (f i) c', f=3)
67
-
68
- return z
69
-
70
-
71
- # Stolen from https://github.com/basujindal/stable-diffusion/blob/main/optimizedSD/splitAttention.py
72
- def _hacked_sliced_attentin_forward(self, x, context=None, mask=None):
73
- h = self.heads
74
-
75
- q = self.to_q(x)
76
- context = default(context, x)
77
- k = self.to_k(context)
78
- v = self.to_v(context)
79
- del context, x
80
-
81
- q, k, v = map(lambda t: einops.rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
82
-
83
- limit = k.shape[0]
84
- att_step = 1
85
- q_chunks = list(torch.tensor_split(q, limit // att_step, dim=0))
86
- k_chunks = list(torch.tensor_split(k, limit // att_step, dim=0))
87
- v_chunks = list(torch.tensor_split(v, limit // att_step, dim=0))
88
-
89
- q_chunks.reverse()
90
- k_chunks.reverse()
91
- v_chunks.reverse()
92
- sim = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device)
93
- del k, q, v
94
- for i in range(0, limit, att_step):
95
- q_buffer = q_chunks.pop()
96
- k_buffer = k_chunks.pop()
97
- v_buffer = v_chunks.pop()
98
- sim_buffer = torch.einsum('b i d, b j d -> b i j', q_buffer, k_buffer) * self.scale
99
-
100
- del k_buffer, q_buffer
101
- # attention, what we cannot get enough of, by chunks
102
-
103
- sim_buffer = sim_buffer.softmax(dim=-1)
104
-
105
- sim_buffer = torch.einsum('b i j, b j d -> b i d', sim_buffer, v_buffer)
106
- del v_buffer
107
- sim[i:i + att_step, :, :] = sim_buffer
108
-
109
- del sim_buffer
110
- sim = einops.rearrange(sim, '(b h) n d -> b n (h d)', h=h)
111
- return self.to_out(sim)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/cldm/model.py DELETED
@@ -1,28 +0,0 @@
1
- import os
2
- import torch
3
-
4
- from omegaconf import OmegaConf
5
- from ldm.util import instantiate_from_config
6
-
7
-
8
- def get_state_dict(d):
9
- return d.get('state_dict', d)
10
-
11
-
12
- def load_state_dict(ckpt_path, location='cpu'):
13
- _, extension = os.path.splitext(ckpt_path)
14
- if extension.lower() == ".safetensors":
15
- import safetensors.torch
16
- state_dict = safetensors.torch.load_file(ckpt_path, device=location)
17
- else:
18
- state_dict = get_state_dict(torch.load(ckpt_path, map_location=torch.device(location)))
19
- state_dict = get_state_dict(state_dict)
20
- print(f'Loaded state_dict from [{ckpt_path}]')
21
- return state_dict
22
-
23
-
24
- def create_model(config_path):
25
- config = OmegaConf.load(config_path)
26
- model = instantiate_from_config(config.model).cpu()
27
- print(f'Loaded model config from [{config_path}]')
28
- return model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/config.py DELETED
@@ -1 +0,0 @@
1
- save_memory = False
 
 
Control-Color/ldm/__pycache__/util.cpython-38.pyc DELETED
Binary file (6.63 kB)
 
Control-Color/ldm/models/__pycache__/autoencoder.cpython-38.pyc DELETED
Binary file (7.63 kB)
 
Control-Color/ldm/models/__pycache__/autoencoder_train.cpython-38.pyc DELETED
Binary file (8.58 kB)
 
Control-Color/ldm/models/autoencoder.py DELETED
@@ -1,220 +0,0 @@
1
- import torch
2
- import pytorch_lightning as pl
3
- import torch.nn.functional as F
4
- from contextlib import contextmanager
5
-
6
- # from ldm.modules.diffusionmodules.model_window import Encoder, Decoder
7
- from ldm.modules.diffusionmodules.model_brefore_dcn import Encoder, Decoder
8
- from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
9
-
10
- from ldm.util import instantiate_from_config
11
- from ldm.modules.ema import LitEma
12
-
13
-
14
- class AutoencoderKL(pl.LightningModule):
15
- def __init__(self,
16
- ddconfig,
17
- lossconfig,
18
- embed_dim,
19
- ckpt_path=None,
20
- ignore_keys=[],
21
- image_key="image",
22
- colorize_nlabels=None,
23
- monitor=None,
24
- ema_decay=None,
25
- learn_logvar=False
26
- ):
27
- super().__init__()
28
- self.learn_logvar = learn_logvar
29
- self.image_key = image_key
30
- self.encoder = Encoder(**ddconfig)
31
- self.decoder = Decoder(**ddconfig)
32
- self.loss = instantiate_from_config(lossconfig)
33
- assert ddconfig["double_z"]
34
- self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
35
- self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
36
- self.embed_dim = embed_dim
37
- if colorize_nlabels is not None:
38
- assert type(colorize_nlabels)==int
39
- self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
40
- if monitor is not None:
41
- self.monitor = monitor
42
-
43
- self.use_ema = ema_decay is not None
44
- if self.use_ema:
45
- self.ema_decay = ema_decay
46
- assert 0. < ema_decay < 1.
47
- self.model_ema = LitEma(self, decay=ema_decay)
48
- print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
49
-
50
- if ckpt_path is not None:
51
- self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
52
-
53
- def init_from_ckpt(self, path, ignore_keys=list()):
54
- sd = torch.load(path, map_location="cpu")["state_dict"]
55
- keys = list(sd.keys())
56
- for k in keys:
57
- for ik in ignore_keys:
58
- if k.startswith(ik):
59
- print("Deleting key {} from state_dict.".format(k))
60
- del sd[k]
61
- self.load_state_dict(sd, strict=False)
62
- print(f"Restored from {path}")
63
-
64
- @contextmanager
65
- def ema_scope(self, context=None):
66
- if self.use_ema:
67
- self.model_ema.store(self.parameters())
68
- self.model_ema.copy_to(self)
69
- if context is not None:
70
- print(f"{context}: Switched to EMA weights")
71
- try:
72
- yield None
73
- finally:
74
- if self.use_ema:
75
- self.model_ema.restore(self.parameters())
76
- if context is not None:
77
- print(f"{context}: Restored training weights")
78
-
79
- def on_train_batch_end(self, *args, **kwargs):
80
- if self.use_ema:
81
- self.model_ema(self)
82
-
83
- def encode(self, x):
84
- h = self.encoder(x)
85
- moments = self.quant_conv(h)
86
- posterior = DiagonalGaussianDistribution(moments)
87
- return posterior
88
-
89
- def decode(self, z):
90
- z = self.post_quant_conv(z)
91
- dec = self.decoder(z)
92
- return dec
93
-
94
- def forward(self, input, sample_posterior=True):
95
- posterior = self.encode(input)
96
- if sample_posterior:
97
- z = posterior.sample()
98
- else:
99
- z = posterior.mode()
100
- dec = self.decode(z)
101
- return dec, posterior
102
-
103
- def get_input(self, batch, k):
104
- x = batch[k]
105
- if len(x.shape) == 3:
106
- x = x[..., None]
107
- x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
108
- return x
109
-
110
- def training_step(self, batch, batch_idx, optimizer_idx):
111
- inputs = self.get_input(batch, self.image_key)
112
- reconstructions, posterior = self(inputs)
113
-
114
- if optimizer_idx == 0:
115
- # train encoder+decoder+logvar
116
- aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
117
- last_layer=self.get_last_layer(), split="train")
118
- self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
119
- self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
120
- return aeloss
121
-
122
- if optimizer_idx == 1:
123
- # train the discriminator
124
- discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
125
- last_layer=self.get_last_layer(), split="train")
126
-
127
- self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
128
- self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
129
- return discloss
130
-
131
- def validation_step(self, batch, batch_idx):
132
- log_dict = self._validation_step(batch, batch_idx)
133
- with self.ema_scope():
134
- log_dict_ema = self._validation_step(batch, batch_idx, postfix="_ema")
135
- return log_dict
136
-
137
- def _validation_step(self, batch, batch_idx, postfix=""):
138
- inputs = self.get_input(batch, self.image_key)
139
- reconstructions, posterior = self(inputs)
140
- aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
141
- last_layer=self.get_last_layer(), split="val"+postfix)
142
-
143
- discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
144
- last_layer=self.get_last_layer(), split="val"+postfix)
145
-
146
- self.log(f"val{postfix}/rec_loss", log_dict_ae[f"val{postfix}/rec_loss"])
147
- self.log_dict(log_dict_ae)
148
- self.log_dict(log_dict_disc)
149
- return self.log_dict
150
-
151
- def configure_optimizers(self):
152
- lr = self.learning_rate
153
- ae_params_list = list(self.encoder.parameters()) + list(self.decoder.parameters()) + list(
154
- self.quant_conv.parameters()) + list(self.post_quant_conv.parameters())
155
- if self.learn_logvar:
156
- print(f"{self.__class__.__name__}: Learning logvar")
157
- ae_params_list.append(self.loss.logvar)
158
- opt_ae = torch.optim.Adam(ae_params_list,
159
- lr=lr, betas=(0.5, 0.9))
160
- opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
161
- lr=lr, betas=(0.5, 0.9))
162
- return [opt_ae, opt_disc], []
163
-
164
- def get_last_layer(self):
165
- return self.decoder.conv_out.weight
166
-
167
- @torch.no_grad()
168
- def log_images(self, batch, only_inputs=False, log_ema=False, **kwargs):
169
- log = dict()
170
- x = self.get_input(batch, self.image_key)
171
- x = x.to(self.device)
172
- if not only_inputs:
173
- xrec, posterior = self(x)
174
- if x.shape[1] > 3:
175
- # colorize with random projection
176
- assert xrec.shape[1] > 3
177
- x = self.to_rgb(x)
178
- xrec = self.to_rgb(xrec)
179
- log["samples"] = self.decode(torch.randn_like(posterior.sample()))
180
- log["reconstructions"] = xrec
181
- if log_ema or self.use_ema:
182
- with self.ema_scope():
183
- xrec_ema, posterior_ema = self(x)
184
- if x.shape[1] > 3:
185
- # colorize with random projection
186
- assert xrec_ema.shape[1] > 3
187
- xrec_ema = self.to_rgb(xrec_ema)
188
- log["samples_ema"] = self.decode(torch.randn_like(posterior_ema.sample()))
189
- log["reconstructions_ema"] = xrec_ema
190
- log["inputs"] = x
191
- return log
192
-
193
- def to_rgb(self, x):
194
- assert self.image_key == "segmentation"
195
- if not hasattr(self, "colorize"):
196
- self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
197
- x = F.conv2d(x, weight=self.colorize)
198
- x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
199
- return x
200
-
201
-
202
- class IdentityFirstStage(torch.nn.Module):
203
- def __init__(self, *args, vq_interface=False, **kwargs):
204
- self.vq_interface = vq_interface
205
- super().__init__()
206
-
207
- def encode(self, x, *args, **kwargs):
208
- return x
209
-
210
- def decode(self, x, *args, **kwargs):
211
- return x
212
-
213
- def quantize(self, x, *args, **kwargs):
214
- if self.vq_interface:
215
- return x, None, [None, None, None]
216
- return x
217
-
218
- def forward(self, x, *args, **kwargs):
219
- return x
220
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/models/autoencoder_train.py DELETED
@@ -1,299 +0,0 @@
1
- import torch
2
- import pytorch_lightning as pl
3
- import torch.nn.functional as F
4
- from contextlib import contextmanager
5
-
6
- from ldm.modules.diffusionmodules.model import Encoder, Decoder
7
- from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
8
-
9
- from ldm.util import instantiate_from_config
10
- from ldm.modules.ema import LitEma
11
-
12
- import random
13
- import cv2
14
-
15
- # from cldm.model import create_model, load_state_dict
16
- # model = create_model('./models/cldm_v15_inpainting.yaml')
17
- # resume_path = "/data/2023text2edit/ControlNet/ckpt_inpainting_from5625+5625/epoch0_global-step3750.ckpt"
18
- # model.load_state_dict(load_state_dict(resume_path, location='cpu'),strict=True)
19
- # model.half()
20
- # model.cuda()
21
-
22
- class AutoencoderKL(pl.LightningModule):
23
- def __init__(self,
24
- ddconfig,
25
- lossconfig,
26
- embed_dim,
27
- ckpt_path=None,
28
- ignore_keys=[],
29
- image_key="input",
30
- output_key="jpg",
31
- gray_image_key="gray",
32
- colorize_nlabels=None,
33
- monitor=None,
34
- ema_decay=None,
35
- learn_logvar=False
36
- ):
37
- super().__init__()
38
- self.learn_logvar = learn_logvar
39
- self.image_key = image_key
40
- self.gray_image_key = gray_image_key
41
- self.output_key=output_key
42
- self.encoder = Encoder(**ddconfig)
43
- self.decoder = Decoder(**ddconfig)
44
- self.loss = instantiate_from_config(lossconfig)
45
- assert ddconfig["double_z"]
46
- self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
47
- self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
48
- self.embed_dim = embed_dim
49
-
50
- # model = create_model('./models/cldm_v15_inpainting.yaml')
51
- # resume_path = "/data/2023text2edit/ControlNet/ckpt_inpainting_from5625+5625/epoch0_global-step3750.ckpt"
52
- # model.load_state_dict(load_state_dict(resume_path, location='cpu'),strict=True)
53
- # model.half()
54
- # self.model=model.cuda()
55
- # # self.model=model.eval()
56
- # for param in self.model.parameters():
57
- # param.requires_grad = False
58
-
59
- if colorize_nlabels is not None:
60
- assert type(colorize_nlabels)==int
61
- self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
62
- if monitor is not None:
63
- self.monitor = monitor
64
-
65
- self.use_ema = ema_decay is not None
66
- if self.use_ema:
67
- self.ema_decay = ema_decay
68
- assert 0. < ema_decay < 1.
69
- self.model_ema = LitEma(self, decay=ema_decay)
70
- print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
71
-
72
- if ckpt_path is not None:
73
- self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
74
-
75
- def init_from_ckpt(self, path, ignore_keys=list()):
76
- sd = torch.load(path, map_location="cpu")["state_dict"]
77
- keys = list(sd.keys())
78
- for k in keys:
79
- for ik in ignore_keys:
80
- if k.startswith(ik):
81
- print("Deleting key {} from state_dict.".format(k))
82
- del sd[k]
83
- self.load_state_dict(sd, strict=False)
84
- print(f"Restored from {path}")
85
-
86
- @contextmanager
87
- def ema_scope(self, context=None):
88
- if self.use_ema:
89
- self.model_ema.store(self.parameters())
90
- self.model_ema.copy_to(self)
91
- if context is not None:
92
- print(f"{context}: Switched to EMA weights")
93
- try:
94
- yield None
95
- finally:
96
- if self.use_ema:
97
- self.model_ema.restore(self.parameters())
98
- if context is not None:
99
- print(f"{context}: Restored training weights")
100
-
101
- def on_train_batch_end(self, *args, **kwargs):
102
- if self.use_ema:
103
- self.model_ema(self)
104
-
105
- def encode(self, x):
106
- h = self.encoder(x)
107
- moments = self.quant_conv(h)
108
- posterior = DiagonalGaussianDistribution(moments)
109
- return posterior
110
-
111
- def decode(self, z,gray_content_z):
112
- z = self.post_quant_conv(z)
113
- gray_content_z = self.post_quant_conv(gray_content_z)
114
- dec = self.decoder(z,gray_content_z)
115
- return dec
116
-
117
- def forward(self, input,gray_image, sample_posterior=True):
118
- posterior = self.encode(input)
119
- if sample_posterior:
120
- z = posterior.sample()
121
- else:
122
- z = posterior.mode()
123
- gray_posterior = self.encode(gray_image)
124
- if sample_posterior:
125
- gray_content_z = gray_posterior.sample()
126
- else:
127
- gray_content_z = gray_posterior.mode()
128
- dec = self.decode(z,gray_content_z)
129
- return dec, posterior
130
-
131
- def get_input(self, batch,k0, k1,k2):
132
- # print(batch)
133
- # print(k)
134
- # x = batch[k]
135
- # if len(x.shape) == 3:
136
- # x = x[..., None]
137
- # x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
138
- gray_image = batch[k2]
139
- if len(gray_image.shape) == 3:
140
- gray_image = gray_image[..., None]
141
- gray_image = gray_image.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
142
-
143
-
144
- # t=random.randint(1,100)#120
145
- # print(t)
146
- # model=model.cuda()
147
- x = batch[k0]#self.model.get_noised_images(((gt.squeeze(0)+1.0)/2.0).permute(2,0,1).to(memory_format=torch.contiguous_format).type(torch.HalfTensor).cuda(),t=torch.Tensor([t]).long().cuda())
148
- x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
149
- # x = x.float()
150
- # torch.cuda.empty_cache()
151
- # print(input.shape)
152
- # cv2.imwrite("tttt.png",cv2.cvtColor(x.squeeze(0).permute(1,2,0).cpu().numpy()*255.0, cv2.COLOR_RGB2BGR))
153
- # x = x*2.0-1.0
154
- # x = x.squeeze(0).permute(1,2,0).cpu().numpy()*2.0-1.0
155
- # if len(x.shape) == 3:
156
- # x = x[..., None]
157
- # x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format)
158
- gt = batch[k1]
159
- if len(gt.shape) == 3:
160
- gt = gt[..., None]
161
- gt = gt.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
162
-
163
- return gt,x,gray_image
164
-
165
- def training_step(self, batch, batch_idx, optimizer_idx):
166
- with torch.no_grad():
167
- outputs,inputs,gray_images = self.get_input(batch, self.image_key,self.output_key,self.gray_image_key)
168
- reconstructions, posterior = self(inputs,gray_images)
169
-
170
- if optimizer_idx == 0:
171
- # train encoder+decoder+logvar
172
- aeloss, log_dict_ae = self.loss(outputs, reconstructions, posterior, optimizer_idx, self.global_step,
173
- last_layer=self.get_last_layer(), split="train")
174
- self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
175
- self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
176
- # print(aeloss)
177
- return aeloss
178
-
179
- if optimizer_idx == 1:
180
- # train the discriminator
181
- discloss, log_dict_disc = self.loss(outputs, reconstructions, posterior, optimizer_idx, self.global_step,
182
- last_layer=self.get_last_layer(), split="train")
183
-
184
- self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
185
- self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
186
- # print(discloss)
187
- return discloss
188
-
189
- def validation_step(self, batch, batch_idx):
190
- log_dict = self._validation_step(batch, batch_idx)
191
- with self.ema_scope():
192
- log_dict_ema = self._validation_step(batch, batch_idx, postfix="_ema")
193
- return log_dict
194
-
195
- def _validation_step(self, batch, batch_idx, postfix=""):
196
- outputs,inputs,gray_images = self.get_input(batch, self.image_key,self.output_key,self.gray_image_key)
197
- reconstructions, posterior = self(inputs,gray_images)
198
- aeloss, log_dict_ae = self.loss(outputs, reconstructions, posterior, 0, self.global_step,
199
- last_layer=self.get_last_layer(), split="val"+postfix)
200
-
201
- discloss, log_dict_disc = self.loss(outputs, reconstructions, posterior, 1, self.global_step,
202
- last_layer=self.get_last_layer(), split="val"+postfix)
203
-
204
- self.log(f"val{postfix}/rec_loss", log_dict_ae[f"val{postfix}/rec_loss"])
205
- self.log_dict(log_dict_ae)
206
- self.log_dict(log_dict_disc)
207
- return self.log_dict
208
-
209
- def configure_optimizers(self):
210
- lr = self.learning_rate
211
- # ae_params_list = list(self.encoder.parameters()) + list(self.decoder.parameters()) + list(
212
- # self.quant_conv.parameters()) + list(self.post_quant_conv.parameters())
213
- # for name,param in self.decoder.named_parameters():
214
- # if "dcn" in name:
215
- # print(name)
216
- ae_params_list = list(self.decoder.dcn_in.parameters())+list(self.decoder.mid.block_1.dcn1.parameters())+list(self.decoder.mid.block_1.dcn2.parameters())+list(self.decoder.mid.block_2.dcn1.parameters())+list(self.decoder.mid.block_2.dcn2.parameters())
217
- # print(ae_params_list)
218
- # for i in ae_params_list:
219
- # print(i)
220
- if self.learn_logvar:
221
- print(f"{self.__class__.__name__}: Learning logvar")
222
- ae_params_list.append(self.loss.logvar)
223
- opt_ae = torch.optim.Adam(ae_params_list,
224
- lr=lr, betas=(0.5, 0.9))
225
- opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
226
- lr=lr, betas=(0.5, 0.9))
227
- return [opt_ae, opt_disc], []
228
-
229
- def get_last_layer(self):
230
- return self.decoder.conv_out.weight
231
-
232
- @torch.no_grad()
233
- def get_gray_content_z(self,gray_image):
234
- # if len(gray_image.shape) == 3:
235
- # gray_image = gray_image[..., None]
236
- gray_image = gray_image.unsqueeze(0).permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
237
- gray_content_z=self.encode(gray_image)
238
- gray_content_z = gray_content_z.sample()
239
- return gray_content_z
240
-
241
- @torch.no_grad()
242
- def log_images(self, batch, only_inputs=False, log_ema=False, **kwargs):
243
- log = dict()
244
- gt,x,gray_image = self.get_input(batch, self.image_key,self.output_key,self.gray_image_key)
245
- log['gt']=gt
246
- x = x.to(self.device)
247
- gray_image = gray_image.to(self.device)
248
- if not only_inputs:
249
- xrec, posterior = self(x,gray_image)
250
- if x.shape[1] > 3:
251
- # colorize with random projection
252
- assert xrec.shape[1] > 3
253
- x = self.to_rgb(x)
254
- gray_image = self.to_rgb(gray_image)
255
- xrec = self.to_rgb(xrec)
256
- gray_content_z=self.encode(gray_image)
257
- gray_content_z = gray_content_z.sample()
258
- log["samples"] = self.decode(torch.randn_like(posterior.sample()),gray_content_z)
259
- log["reconstructions"] = xrec
260
- if log_ema or self.use_ema:
261
- with self.ema_scope():
262
- xrec_ema, posterior_ema = self(x)
263
- if x.shape[1] > 3:
264
- # colorize with random projection
265
- assert xrec_ema.shape[1] > 3
266
- xrec_ema = self.to_rgb(xrec_ema)
267
- log["samples_ema"] = self.decode(torch.randn_like(posterior_ema.sample()))
268
- log["reconstructions_ema"] = xrec_ema
269
- log["inputs"] = x
270
- return log
271
-
272
- def to_rgb(self, x):
273
- assert self.image_key == "segmentation"
274
- if not hasattr(self, "colorize"):
275
- self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
276
- x = F.conv2d(x, weight=self.colorize)
277
- x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
278
- return x
279
-
280
-
281
- class IdentityFirstStage(torch.nn.Module):
282
- def __init__(self, *args, vq_interface=False, **kwargs):
283
- self.vq_interface = vq_interface
284
- super().__init__()
285
-
286
- def encode(self, x, *args, **kwargs):
287
- return x
288
-
289
- def decode(self, x, *args, **kwargs):
290
- return x
291
-
292
- def quantize(self, x, *args, **kwargs):
293
- if self.vq_interface:
294
- return x, None, [None, None, None]
295
- return x
296
-
297
- def forward(self, x, *args, **kwargs):
298
- return x
299
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/models/diffusion/__init__.py DELETED
File without changes
Control-Color/ldm/models/diffusion/__pycache__/__init__.cpython-38.pyc DELETED
Binary file (162 Bytes)
 
Control-Color/ldm/models/diffusion/__pycache__/ddim.cpython-38.pyc DELETED
Binary file (9.25 kB)
 
Control-Color/ldm/models/diffusion/__pycache__/ddpm.cpython-38.pyc DELETED
Binary file (55.8 kB)
 
Control-Color/ldm/models/diffusion/__pycache__/ddpm_nonoise.cpython-38.pyc DELETED
Binary file (54.9 kB)
 
Control-Color/ldm/models/diffusion/ddim.py DELETED
@@ -1,337 +0,0 @@
1
- """SAMPLING ONLY."""
2
-
3
- import torch
4
- import numpy as np
5
- from tqdm import tqdm
6
-
7
- from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
8
-
9
-
10
- class DDIMSampler(object):
11
- def __init__(self, model, schedule="linear", **kwargs):
12
- super().__init__()
13
- self.model = model
14
- self.ddpm_num_timesteps = model.num_timesteps
15
- self.schedule = schedule
16
-
17
- def register_buffer(self, name, attr):
18
- if type(attr) == torch.Tensor:
19
- if attr.device != torch.device("cuda"):
20
- attr = attr.to(torch.device("cuda"))
21
- setattr(self, name, attr)
22
-
23
- def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
24
- self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
25
- num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
26
- alphas_cumprod = self.model.alphas_cumprod
27
- assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
28
- to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
29
-
30
- self.register_buffer('betas', to_torch(self.model.betas))
31
- self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
32
- self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
33
-
34
- # calculations for diffusion q(x_t | x_{t-1}) and others
35
- self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
36
- self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
37
- self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
38
- self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
39
- self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
40
-
41
- # ddim sampling parameters
42
- ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
43
- ddim_timesteps=self.ddim_timesteps,
44
- eta=ddim_eta,verbose=verbose)
45
- self.register_buffer('ddim_sigmas', ddim_sigmas)
46
- self.register_buffer('ddim_alphas', ddim_alphas)
47
- self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
48
- self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
49
- sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
50
- (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
51
- 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
52
- self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
53
-
54
- @torch.no_grad()
55
- def sample(self,
56
- S,
57
- batch_size,
58
- shape,
59
- conditioning=None,
60
- callback=None,
61
- normals_sequence=None,
62
- img_callback=None,
63
- quantize_x0=False,
64
- eta=0.,
65
- mask=None,
66
- masked_image_latents=None,
67
- x0=None,
68
- temperature=1.,
69
- noise_dropout=0.,
70
- score_corrector=None,
71
- corrector_kwargs=None,
72
- verbose=True,
73
- x_T=None,
74
- log_every_t=100,
75
- unconditional_guidance_scale=1.,
76
- unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
77
- dynamic_threshold=None,
78
- ucg_schedule=None,
79
- **kwargs
80
- ):
81
- if conditioning is not None:
82
- if isinstance(conditioning, dict):
83
- ctmp = conditioning[list(conditioning.keys())[0]]
84
- while isinstance(ctmp, list): ctmp = ctmp[0]
85
- cbs = ctmp.shape[0]
86
- if cbs != batch_size:
87
- print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
88
-
89
- elif isinstance(conditioning, list):
90
- for ctmp in conditioning:
91
- if ctmp.shape[0] != batch_size:
92
- print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
93
-
94
- else:
95
- if conditioning.shape[0] != batch_size:
96
- print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
97
-
98
- self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
99
- # sampling
100
- C, H, W = shape
101
- size = (batch_size, C, H, W)
102
- print(f'Data shape for DDIM sampling is {size}, eta {eta}')
103
-
104
- samples, intermediates = self.ddim_sampling(conditioning, size,
105
- callback=callback,
106
- img_callback=img_callback,
107
- quantize_denoised=quantize_x0,
108
- mask=mask,masked_image_latents=masked_image_latents, x0=x0,
109
- ddim_use_original_steps=False,
110
- noise_dropout=noise_dropout,
111
- temperature=temperature,
112
- score_corrector=score_corrector,
113
- corrector_kwargs=corrector_kwargs,
114
- x_T=x_T,
115
- log_every_t=log_every_t,
116
- unconditional_guidance_scale=unconditional_guidance_scale,
117
- unconditional_conditioning=unconditional_conditioning,
118
- dynamic_threshold=dynamic_threshold,
119
- ucg_schedule=ucg_schedule
120
- )
121
- return samples, intermediates
122
-
123
- @torch.no_grad()
124
- def ddim_sampling(self, cond, shape,
125
- x_T=None, ddim_use_original_steps=False,
126
- callback=None, timesteps=None, quantize_denoised=False,
127
- mask=None,masked_image_latents=None, x0=None, img_callback=None, log_every_t=100,
128
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
129
- unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,
130
- ucg_schedule=None):
131
- device = self.model.betas.device
132
- b = shape[0]
133
- if x_T is None:
134
- img = torch.randn(shape, device=device)
135
- else:
136
- img = x_T
137
-
138
- if timesteps is None:
139
- timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
140
- elif timesteps is not None and not ddim_use_original_steps:
141
- subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
142
- timesteps = self.ddim_timesteps[:subset_end]
143
-
144
- intermediates = {'x_inter': [img], 'pred_x0': [img]}
145
- time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
146
- total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
147
- print(f"Running DDIM Sampling with {total_steps} timesteps")
148
-
149
- iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
150
-
151
- for i, step in enumerate(iterator):
152
- index = total_steps - i - 1
153
- ts = torch.full((b,), step, device=device, dtype=torch.long)
154
-
155
- # if mask is not None:
156
- # assert x0 is not None
157
- # img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
158
- # img = img_orig * mask + (1. - mask) * img
159
-
160
- if ucg_schedule is not None:
161
- assert len(ucg_schedule) == len(time_range)
162
- unconditional_guidance_scale = ucg_schedule[i]
163
-
164
- outs = self.p_sample_ddim(img,mask,masked_image_latents, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
165
- quantize_denoised=quantize_denoised, temperature=temperature,
166
- noise_dropout=noise_dropout, score_corrector=score_corrector,
167
- corrector_kwargs=corrector_kwargs,
168
- unconditional_guidance_scale=unconditional_guidance_scale,
169
- unconditional_conditioning=unconditional_conditioning,
170
- dynamic_threshold=dynamic_threshold)
171
- img, pred_x0 = outs
172
- if callback: callback(i)
173
- if img_callback: img_callback(pred_x0, i)
174
-
175
- if index % log_every_t == 0 or index == total_steps - 1:
176
- intermediates['x_inter'].append(img)
177
- intermediates['pred_x0'].append(pred_x0)
178
-
179
- return img, intermediates
180
-
181
- @torch.no_grad()
182
- def p_sample_ddim(self, x,mask,masked_image_latents, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
183
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
184
- unconditional_guidance_scale=1., unconditional_conditioning=None,
185
- dynamic_threshold=None):
186
- b, *_, device = *x.shape, x.device
187
-
188
- if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
189
- model_output = self.model.apply_model(x,mask,masked_image_latents, t, c)
190
- else:
191
- x_in = torch.cat([x] * 2)
192
- t_in = torch.cat([t] * 2)
193
- if isinstance(c, dict):
194
- assert isinstance(unconditional_conditioning, dict)
195
- c_in = dict()
196
- for k in c:
197
- if isinstance(c[k], list):
198
- c_in[k] = [torch.cat([
199
- unconditional_conditioning[k][i],
200
- c[k][i]]) for i in range(len(c[k]))]
201
- else:
202
- c_in[k] = torch.cat([
203
- unconditional_conditioning[k],
204
- c[k]])
205
- elif isinstance(c, list):
206
- c_in = list()
207
- assert isinstance(unconditional_conditioning, list)
208
- for i in range(len(c)):
209
- c_in.append(torch.cat([unconditional_conditioning[i], c[i]]))
210
- else:
211
- c_in = torch.cat([unconditional_conditioning, c])
212
- model_uncond, model_t = self.model.apply_model(x_in,mask,masked_image_latents, t_in, c_in).chunk(2)
213
- model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
214
-
215
- if self.model.parameterization == "v":
216
- e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
217
- else:
218
- e_t = model_output
219
-
220
- if score_corrector is not None:
221
- assert self.model.parameterization == "eps", 'not implemented'
222
- e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
223
-
224
- alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
225
- alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
226
- sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
227
- sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
228
- # select parameters corresponding to the currently considered timestep
229
- a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
230
- a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
231
- sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
232
- sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
233
-
234
- # current prediction for x_0
235
- if self.model.parameterization != "v":
236
- pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
237
- else:
238
- pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
239
-
240
- if quantize_denoised:
241
- pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
242
-
243
- if dynamic_threshold is not None:
244
- raise NotImplementedError()
245
-
246
- # direction pointing to x_t
247
- dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
248
- noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
249
- if noise_dropout > 0.:
250
- noise = torch.nn.functional.dropout(noise, p=noise_dropout)
251
- x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
252
- return x_prev, pred_x0
253
-
254
- @torch.no_grad()
255
- def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
256
- unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
257
- num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0]
258
-
259
- assert t_enc <= num_reference_steps
260
- num_steps = t_enc
261
-
262
- if use_original_steps:
263
- alphas_next = self.alphas_cumprod[:num_steps]
264
- alphas = self.alphas_cumprod_prev[:num_steps]
265
- else:
266
- alphas_next = self.ddim_alphas[:num_steps]
267
- alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
268
-
269
- x_next = x0
270
- intermediates = []
271
- inter_steps = []
272
- for i in tqdm(range(num_steps), desc='Encoding Image'):
273
- t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long)
274
- if unconditional_guidance_scale == 1.:
275
- noise_pred = self.model.apply_model(x_next, t, c)
276
- else:
277
- assert unconditional_conditioning is not None
278
- e_t_uncond, noise_pred = torch.chunk(
279
- self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
280
- torch.cat((unconditional_conditioning, c))), 2)
281
- noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
282
-
283
- xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
284
- weighted_noise_pred = alphas_next[i].sqrt() * (
285
- (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
286
- x_next = xt_weighted + weighted_noise_pred
287
- if return_intermediates and i % (
288
- num_steps // return_intermediates) == 0 and i < num_steps - 1:
289
- intermediates.append(x_next)
290
- inter_steps.append(i)
291
- elif return_intermediates and i >= num_steps - 2:
292
- intermediates.append(x_next)
293
- inter_steps.append(i)
294
- if callback: callback(i)
295
-
296
- out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
297
- if return_intermediates:
298
- out.update({'intermediates': intermediates})
299
- return x_next, out
300
-
301
- @torch.no_grad()
302
- def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
303
- # fast, but does not allow for exact reconstruction
304
- # t serves as an index to gather the correct alphas
305
- if use_original_steps:
306
- sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
307
- sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
308
- else:
309
- sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
310
- sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
311
-
312
- if noise is None:
313
- noise = torch.randn_like(x0)
314
- return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
315
- extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
316
-
317
- @torch.no_grad()
318
- def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
319
- use_original_steps=False, callback=None):
320
-
321
- timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
322
- timesteps = timesteps[:t_start]
323
-
324
- time_range = np.flip(timesteps)
325
- total_steps = timesteps.shape[0]
326
- print(f"Running DDIM Sampling with {total_steps} timesteps")
327
-
328
- iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
329
- x_dec = x_latent
330
- for i, step in enumerate(iterator):
331
- index = total_steps - i - 1
332
- ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
333
- x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
334
- unconditional_guidance_scale=unconditional_guidance_scale,
335
- unconditional_conditioning=unconditional_conditioning)
336
- if callback: callback(i)
337
- return x_dec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/models/diffusion/ddpm.py DELETED
@@ -1,1911 +0,0 @@
1
- """
2
- wild mixture of
3
- https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
4
- https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
5
- https://github.com/CompVis/taming-transformers
6
- -- merci
7
- """
8
-
9
- import torch
10
- import torch.nn as nn
11
- import numpy as np
12
- import pytorch_lightning as pl
13
- from torch.optim.lr_scheduler import LambdaLR
14
- from einops import rearrange, repeat
15
- from contextlib import contextmanager, nullcontext
16
- from functools import partial
17
- import itertools
18
- from tqdm import tqdm
19
- from torchvision.utils import make_grid
20
- from pytorch_lightning.utilities.distributed import rank_zero_only
21
- from omegaconf import ListConfig
22
-
23
- from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
24
- from ldm.modules.ema import LitEma
25
- from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
26
- from ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL
27
- from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
28
- from ldm.models.diffusion.ddim import DDIMSampler
29
-
30
-
31
- __conditioning_keys__ = {'concat': 'c_concat',
32
- 'crossattn': 'c_crossattn',
33
- 'adm': 'y'}
34
-
35
-
36
- def disabled_train(self, mode=True):
37
- """Overwrite model.train with this function to make sure train/eval mode
38
- does not change anymore."""
39
- return self
40
-
41
-
42
- def uniform_on_device(r1, r2, shape, device):
43
- return (r1 - r2) * torch.rand(*shape, device=device) + r2
44
-
45
- def prepare_mask_latents(
46
- mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
47
- ):
48
- # resize the mask to latents shape as we concatenate the mask to the latents
49
- # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
50
- # and half precision
51
- mask = torch.nn.functional.interpolate(
52
- mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor)
53
- )
54
- mask = mask.to(device=device, dtype=dtype)
55
-
56
- masked_image = masked_image.to(device=device, dtype=dtype)
57
-
58
- # encode the mask image into latents space so we can concatenate it to the latents
59
- if isinstance(generator, list):
60
- masked_image_latents = [
61
- self.vae.encode(masked_image[i : i + 1]).latent_dist.sample(generator=generator[i])
62
- for i in range(batch_size)
63
- ]
64
- masked_image_latents = torch.cat(masked_image_latents, dim=0)
65
- else:
66
- masked_image_latents = self.vae.encode(masked_image).latent_dist.sample(generator=generator)
67
- masked_image_latents = self.vae.config.scaling_factor * masked_image_latents
68
-
69
- # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
70
- if mask.shape[0] < batch_size:
71
- if not batch_size % mask.shape[0] == 0:
72
- raise ValueError(
73
- "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
74
- f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
75
- " of masks that you pass is divisible by the total requested batch size."
76
- )
77
- mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
78
- if masked_image_latents.shape[0] < batch_size:
79
- if not batch_size % masked_image_latents.shape[0] == 0:
80
- raise ValueError(
81
- "The passed images and the required batch size don't match. Images are supposed to be duplicated"
82
- f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
83
- " Make sure the number of images that you pass is divisible by the total requested batch size."
84
- )
85
- masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
86
-
87
- mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
88
- masked_image_latents = (
89
- torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
90
- )
91
-
92
- # aligning device to prevent device errors when concating it with the latent model input
93
- masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
94
- return mask, masked_image_latents
95
-
96
- class DDPM(pl.LightningModule):
97
- # classic DDPM with Gaussian diffusion, in image space
98
- def __init__(self,
99
- unet_config,
100
- timesteps=1000,
101
- beta_schedule="linear",
102
- loss_type="l2",
103
- ckpt_path=None,
104
- ignore_keys=[],
105
- load_only_unet=False,
106
- monitor="val/loss",
107
- use_ema=True,
108
- first_stage_key="image",
109
- image_size=256,
110
- channels=3,
111
- log_every_t=100,
112
- clip_denoised=True,
113
- linear_start=1e-4,
114
- linear_end=2e-2,
115
- cosine_s=8e-3,
116
- given_betas=None,
117
- original_elbo_weight=0.,
118
- v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
119
- l_simple_weight=1.,
120
- conditioning_key=None,
121
- parameterization="eps", # all assuming fixed variance schedules
122
- scheduler_config=None,
123
- use_positional_encodings=False,
124
- learn_logvar=False,
125
- logvar_init=0.,
126
- make_it_fit=False,
127
- ucg_training=None,
128
- reset_ema=False,
129
- reset_num_ema_updates=False,
130
- ):
131
- super().__init__()
132
- assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"'
133
- self.parameterization = parameterization
134
- print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
135
- self.cond_stage_model = None
136
- self.clip_denoised = clip_denoised
137
- self.log_every_t = log_every_t
138
- self.first_stage_key = first_stage_key
139
- self.image_size = image_size # try conv?
140
- self.channels = channels
141
- self.use_positional_encodings = use_positional_encodings
142
- self.model = DiffusionWrapper(unet_config, conditioning_key)
143
- count_params(self.model, verbose=True)
144
- self.use_ema = use_ema
145
- if self.use_ema:
146
- self.model_ema = LitEma(self.model)
147
- print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
148
-
149
- self.use_scheduler = scheduler_config is not None
150
- if self.use_scheduler:
151
- self.scheduler_config = scheduler_config
152
-
153
- self.v_posterior = v_posterior
154
- self.original_elbo_weight = original_elbo_weight
155
- self.l_simple_weight = l_simple_weight
156
-
157
- if monitor is not None:
158
- self.monitor = monitor
159
- self.make_it_fit = make_it_fit
160
- if reset_ema: assert exists(ckpt_path)
161
- if ckpt_path is not None:
162
- self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
163
- if reset_ema:
164
- assert self.use_ema
165
- print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.")
166
- self.model_ema = LitEma(self.model)
167
- if reset_num_ema_updates:
168
- print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ")
169
- assert self.use_ema
170
- self.model_ema.reset_num_updates()
171
-
172
- self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
173
- linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
174
-
175
- self.loss_type = loss_type
176
-
177
- self.learn_logvar = learn_logvar
178
- logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
179
- if self.learn_logvar:
180
- self.logvar = nn.Parameter(self.logvar, requires_grad=True)
181
- else:
182
- self.register_buffer('logvar', logvar)
183
-
184
- self.ucg_training = ucg_training or dict()
185
- if self.ucg_training:
186
- self.ucg_prng = np.random.RandomState()
187
-
188
- def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
189
- linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
190
- if exists(given_betas):
191
- betas = given_betas
192
- else:
193
- betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
194
- cosine_s=cosine_s)
195
- alphas = 1. - betas
196
- alphas_cumprod = np.cumprod(alphas, axis=0)
197
- alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
198
-
199
- timesteps, = betas.shape
200
- self.num_timesteps = int(timesteps)
201
- self.linear_start = linear_start
202
- self.linear_end = linear_end
203
- assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
204
-
205
- to_torch = partial(torch.tensor, dtype=torch.float32)
206
-
207
- self.register_buffer('betas', to_torch(betas))
208
- self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
209
- self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
210
-
211
- # calculations for diffusion q(x_t | x_{t-1}) and others
212
- self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
213
- self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
214
- self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
215
- self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
216
- self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
217
-
218
- # calculations for posterior q(x_{t-1} | x_t, x_0)
219
- posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
220
- 1. - alphas_cumprod) + self.v_posterior * betas
221
- # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
222
- self.register_buffer('posterior_variance', to_torch(posterior_variance))
223
- # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
224
- self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
225
- self.register_buffer('posterior_mean_coef1', to_torch(
226
- betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
227
- self.register_buffer('posterior_mean_coef2', to_torch(
228
- (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
229
-
230
- if self.parameterization == "eps":
231
- lvlb_weights = self.betas ** 2 / (
232
- 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
233
- elif self.parameterization == "x0":
234
- lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
235
- elif self.parameterization == "v":
236
- lvlb_weights = torch.ones_like(self.betas ** 2 / (
237
- 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)))
238
- else:
239
- raise NotImplementedError("mu not supported")
240
- lvlb_weights[0] = lvlb_weights[1]
241
- self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
242
- assert not torch.isnan(self.lvlb_weights).all()
243
-
244
- @contextmanager
245
- def ema_scope(self, context=None):
246
- if self.use_ema:
247
- self.model_ema.store(self.model.parameters())
248
- self.model_ema.copy_to(self.model)
249
- if context is not None:
250
- print(f"{context}: Switched to EMA weights")
251
- try:
252
- yield None
253
- finally:
254
- if self.use_ema:
255
- self.model_ema.restore(self.model.parameters())
256
- if context is not None:
257
- print(f"{context}: Restored training weights")
258
-
259
- @torch.no_grad()
260
- def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
261
- sd = torch.load(path, map_location="cpu")
262
- if "state_dict" in list(sd.keys()):
263
- sd = sd["state_dict"]
264
- keys = list(sd.keys())
265
- for k in keys:
266
- for ik in ignore_keys:
267
- if k.startswith(ik):
268
- print("Deleting key {} from state_dict.".format(k))
269
- del sd[k]
270
- if self.make_it_fit:
271
- n_params = len([name for name, _ in
272
- itertools.chain(self.named_parameters(),
273
- self.named_buffers())])
274
- for name, param in tqdm(
275
- itertools.chain(self.named_parameters(),
276
- self.named_buffers()),
277
- desc="Fitting old weights to new weights",
278
- total=n_params
279
- ):
280
- if not name in sd:
281
- continue
282
- old_shape = sd[name].shape
283
- new_shape = param.shape
284
- assert len(old_shape) == len(new_shape)
285
- if len(new_shape) > 2:
286
- # we only modify first two axes
287
- assert new_shape[2:] == old_shape[2:]
288
- # assumes first axis corresponds to output dim
289
- if not new_shape == old_shape:
290
- new_param = param.clone()
291
- old_param = sd[name]
292
- if len(new_shape) == 1:
293
- for i in range(new_param.shape[0]):
294
- new_param[i] = old_param[i % old_shape[0]]
295
- elif len(new_shape) >= 2:
296
- for i in range(new_param.shape[0]):
297
- for j in range(new_param.shape[1]):
298
- new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]]
299
-
300
- n_used_old = torch.ones(old_shape[1])
301
- for j in range(new_param.shape[1]):
302
- n_used_old[j % old_shape[1]] += 1
303
- n_used_new = torch.zeros(new_shape[1])
304
- for j in range(new_param.shape[1]):
305
- n_used_new[j] = n_used_old[j % old_shape[1]]
306
-
307
- n_used_new = n_used_new[None, :]
308
- while len(n_used_new.shape) < len(new_shape):
309
- n_used_new = n_used_new.unsqueeze(-1)
310
- new_param /= n_used_new
311
-
312
- sd[name] = new_param
313
-
314
- missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
315
- sd, strict=False)
316
- print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
317
- if len(missing) > 0:
318
- print(f"Missing Keys:\n {missing}")
319
- if len(unexpected) > 0:
320
- print(f"\nUnexpected Keys:\n {unexpected}")
321
-
322
- def q_mean_variance(self, x_start, t):
323
- """
324
- Get the distribution q(x_t | x_0).
325
- :param x_start: the [N x C x ...] tensor of noiseless inputs.
326
- :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
327
- :return: A tuple (mean, variance, log_variance), all of x_start's shape.
328
- """
329
- mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
330
- variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
331
- log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
332
- return mean, variance, log_variance
333
-
334
- def predict_start_from_noise(self, x_t, t, noise):
335
- return (
336
- extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
337
- extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
338
- )
339
-
340
- def predict_start_from_z_and_v(self, x_t, t, v):
341
- # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
342
- # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
343
- return (
344
- extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t -
345
- extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v
346
- )
347
-
348
- # def get_x_t_from_start_and_t(self, start, t, v):
349
- # return (
350
- # (start+extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, start.shape) * v)/extract_into_tensor(self.sqrt_alphas_cumprod, t, start.shape)
351
- # )
352
-
353
- def predict_eps_from_z_and_v(self, x_t, t, v):
354
- return (
355
- extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v +
356
- extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t
357
- )
358
-
359
- def q_posterior(self, x_start, x_t, t):
360
- posterior_mean = (
361
- extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
362
- extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
363
- )
364
- posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
365
- posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
366
- return posterior_mean, posterior_variance, posterior_log_variance_clipped
367
-
368
- def p_mean_variance(self, x, t, clip_denoised: bool):
369
- model_out = self.model(x, t)
370
- if self.parameterization == "eps":
371
- x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
372
- elif self.parameterization == "x0":
373
- x_recon = model_out
374
- if clip_denoised:
375
- x_recon.clamp_(-1., 1.)
376
-
377
- model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
378
- return model_mean, posterior_variance, posterior_log_variance
379
-
380
- @torch.no_grad()
381
- def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
382
- b, *_, device = *x.shape, x.device
383
- model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
384
- noise = noise_like(x.shape, device, repeat_noise)
385
- # no noise when t == 0
386
- nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
387
- return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
388
-
389
- @torch.no_grad()
390
- def p_sample_loop(self, shape, return_intermediates=False):
391
- device = self.betas.device
392
- b = shape[0]
393
- img = torch.randn(shape, device=device)
394
- intermediates = [img]
395
- for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
396
- img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
397
- clip_denoised=self.clip_denoised)
398
- if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
399
- intermediates.append(img)
400
- if return_intermediates:
401
- return img, intermediates
402
- return img
403
-
404
- @torch.no_grad()
405
- def sample(self, batch_size=16, return_intermediates=False):
406
- image_size = self.image_size
407
- channels = self.channels
408
- return self.p_sample_loop((batch_size, channels, image_size, image_size),
409
- return_intermediates=return_intermediates)
410
-
411
- def q_sample(self, x_start, t, noise=None):
412
- noise = default(noise, lambda: torch.randn_like(x_start))
413
- return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
414
- extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
415
-
416
- def get_v(self, x, noise, t):
417
- return (
418
- extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise -
419
- extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
420
- )
421
-
422
- def get_loss(self, pred, target, mean=True):
423
- if self.loss_type == 'l1':
424
- loss = (target - pred).abs()
425
- if mean:
426
- loss = loss.mean()
427
- elif self.loss_type == 'l2':
428
- if mean:
429
- loss = torch.nn.functional.mse_loss(target, pred)
430
- else:
431
- loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
432
- else:
433
- raise NotImplementedError("unknown loss type '{loss_type}'")
434
-
435
- return loss
436
-
437
- def p_losses(self, x_start, t, noise=None):
438
- noise = default(noise, lambda: torch.randn_like(x_start))
439
- x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
440
- model_out = self.model(x_noisy, t)
441
-
442
- loss_dict = {}
443
- if self.parameterization == "eps":
444
- target = noise
445
- elif self.parameterization == "x0":
446
- target = x_start
447
- elif self.parameterization == "v":
448
- target = self.get_v(x_start, noise, t)
449
- else:
450
- raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported")
451
-
452
- loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
453
-
454
- log_prefix = 'train' if self.training else 'val'
455
-
456
- loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
457
- loss_simple = loss.mean() * self.l_simple_weight
458
-
459
- loss_vlb = (self.lvlb_weights[t] * loss).mean()
460
- loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
461
-
462
- loss = loss_simple + self.original_elbo_weight * loss_vlb
463
-
464
- loss_dict.update({f'{log_prefix}/loss': loss})
465
-
466
- return loss, loss_dict
467
-
468
- def forward(self, x, *args, **kwargs):
469
- # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
470
- # assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
471
- t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
472
- return self.p_losses(x, t, *args, **kwargs)
473
-
474
- def get_input(self, batch, k):
475
- x = batch[k]
476
- if len(x.shape) == 3:
477
- x = x[..., None]
478
- x = rearrange(x, 'b h w c -> b c h w')
479
- x = x.to(memory_format=torch.contiguous_format).float()
480
- return x
481
-
482
- def shared_step(self, batch):
483
- x = self.get_input(batch, self.first_stage_key)
484
- loss, loss_dict = self(x)
485
- return loss, loss_dict
486
-
487
- def training_step(self, batch, batch_idx):
488
- for k in self.ucg_training:
489
- p = self.ucg_training[k]["p"]
490
- val = self.ucg_training[k]["val"]
491
- if val is None:
492
- val = ""
493
- for i in range(len(batch[k])):
494
- if self.ucg_prng.choice(2, p=[1 - p, p]):
495
- batch[k][i] = val
496
-
497
- loss, loss_dict = self.shared_step(batch)
498
-
499
- self.log_dict(loss_dict, prog_bar=True,
500
- logger=True, on_step=True, on_epoch=True)
501
-
502
- self.log("global_step", self.global_step,
503
- prog_bar=True, logger=True, on_step=True, on_epoch=False)
504
-
505
- if self.use_scheduler:
506
- lr = self.optimizers().param_groups[0]['lr']
507
- self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
508
-
509
- return loss
510
-
511
- @torch.no_grad()
512
- def validation_step(self, batch, batch_idx):
513
- _, loss_dict_no_ema = self.shared_step(batch)
514
- with self.ema_scope():
515
- _, loss_dict_ema = self.shared_step(batch)
516
- loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
517
- self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
518
- self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
519
-
520
- def on_train_batch_end(self, *args, **kwargs):
521
- if self.use_ema:
522
- self.model_ema(self.model)
523
-
524
- def _get_rows_from_list(self, samples):
525
- n_imgs_per_row = len(samples)
526
- denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
527
- denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
528
- denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
529
- return denoise_grid
530
-
531
- @torch.no_grad()
532
- def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
533
- log = dict()
534
- x = self.get_input(batch, self.first_stage_key)
535
- N = min(x.shape[0], N)
536
- n_row = min(x.shape[0], n_row)
537
- x = x.to(self.device)[:N]
538
- log["inputs"] = x
539
-
540
- # get diffusion row
541
- diffusion_row = list()
542
- x_start = x[:n_row]
543
-
544
- for t in range(self.num_timesteps):
545
- if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
546
- t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
547
- t = t.to(self.device).long()
548
- noise = torch.randn_like(x_start)
549
- x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
550
- diffusion_row.append(x_noisy)
551
-
552
- log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
553
-
554
- if sample:
555
- # get denoise row
556
- with self.ema_scope("Plotting"):
557
- samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
558
-
559
- log["samples"] = samples
560
- log["denoise_row"] = self._get_rows_from_list(denoise_row)
561
-
562
- if return_keys:
563
- if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
564
- return log
565
- else:
566
- return {key: log[key] for key in return_keys}
567
- return log
568
-
569
- def configure_optimizers(self):
570
- lr = self.learning_rate
571
- params = list(self.model.parameters())
572
- if self.learn_logvar:
573
- params = params + [self.logvar]
574
- opt = torch.optim.AdamW(params, lr=lr)
575
- return opt
576
-
577
-
578
- class LatentDiffusion(DDPM):
579
- """main class"""
580
-
581
- def __init__(self,
582
- first_stage_config,
583
- cond_stage_config,
584
- contextual_stage_config,
585
- num_timesteps_cond=None,
586
- cond_stage_key="image",
587
- cond_stage_trainable=False,
588
- concat_mode=True,
589
- cond_stage_forward=None,
590
- conditioning_key=None,
591
- scale_factor=1.0,
592
- scale_by_std=False,
593
- force_null_conditioning=False,
594
- masked_image=None,
595
- mask=None,
596
- load_loss=False,
597
- *args, **kwargs):
598
- self.masked_image=masked_image
599
- self.mask=mask
600
- self.load_loss=load_loss
601
- self.force_null_conditioning = force_null_conditioning
602
- self.num_timesteps_cond = default(num_timesteps_cond, 1)
603
- self.scale_by_std = scale_by_std
604
- assert self.num_timesteps_cond <= kwargs['timesteps']
605
- # for backwards compatibility after implementation of DiffusionWrapper
606
- if conditioning_key is None:
607
- conditioning_key = 'concat' if concat_mode else 'crossattn'
608
- if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning:
609
- conditioning_key = None
610
- ckpt_path = kwargs.pop("ckpt_path", None)
611
- reset_ema = kwargs.pop("reset_ema", False)
612
- reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False)
613
- ignore_keys = kwargs.pop("ignore_keys", [])
614
- # print(conditioning_key)
615
- super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
616
- self.concat_mode = concat_mode
617
- self.cond_stage_trainable = cond_stage_trainable
618
- self.cond_stage_key = cond_stage_key
619
- try:
620
- self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
621
- except:
622
- self.num_downs = 0
623
- if not scale_by_std:
624
- self.scale_factor = scale_factor
625
- else:
626
- self.register_buffer('scale_factor', torch.tensor(scale_factor))
627
- self.instantiate_first_stage(first_stage_config)
628
- self.instantiate_cond_stage(cond_stage_config)
629
- self.instantiate_contextual_stage(contextual_stage_config)
630
- self.cond_stage_forward = cond_stage_forward
631
- self.clip_denoised = False
632
- self.bbox_tokenizer = None
633
-
634
- self.restarted_from_ckpt = False
635
- if ckpt_path is not None:
636
- self.init_from_ckpt(ckpt_path, ignore_keys)
637
- self.restarted_from_ckpt = True
638
- if reset_ema:
639
- assert self.use_ema
640
- print(
641
- f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.")
642
- self.model_ema = LitEma(self.model)
643
- if reset_num_ema_updates:
644
- print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ")
645
- assert self.use_ema
646
- self.model_ema.reset_num_updates()
647
-
648
- def make_cond_schedule(self, ):
649
- self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
650
- ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
651
- self.cond_ids[:self.num_timesteps_cond] = ids
652
-
653
- @rank_zero_only
654
- @torch.no_grad()
655
- def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
656
- # only for very first batch
657
- if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:
658
- assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
659
- # set rescale weight to 1./std of encodings
660
- print("### USING STD-RESCALING ###")
661
- x = super().get_input(batch, self.first_stage_key)
662
- x = x.to(self.device)
663
- encoder_posterior = self.encode_first_stage(x)
664
- z = self.get_first_stage_encoding(encoder_posterior).detach()
665
- del self.scale_factor
666
- self.register_buffer('scale_factor', 1. / z.flatten().std())
667
- print(f"setting self.scale_factor to {self.scale_factor}")
668
- print("### USING STD-RESCALING ###")
669
-
670
- def register_schedule(self,
671
- given_betas=None, beta_schedule="linear", timesteps=1000,
672
- linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
673
- super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
674
-
675
- self.shorten_cond_schedule = self.num_timesteps_cond > 1
676
- if self.shorten_cond_schedule:
677
- self.make_cond_schedule()
678
-
679
- def instantiate_first_stage(self, config):
680
- model = instantiate_from_config(config)
681
- self.first_stage_model = model.eval()
682
- self.first_stage_model.train = disabled_train
683
- for param in self.first_stage_model.parameters():
684
- param.requires_grad = False
685
-
686
- def instantiate_contextual_stage(self, config):
687
- if self.load_loss==True:
688
- model = instantiate_from_config(config)
689
- model.load_state_dict(torch.load("/mnt/lustre/zxliang/zcli/data/vgg19_conv.pth"), strict=False)
690
- print("vgg loaded")
691
- self.contextual_stage_model = model.eval()
692
- for param in self.contextual_stage_model.parameters():
693
- param.requires_grad = False
694
- self.contextual_loss = ContextualLoss().to(self.device)
695
- elif self.load_loss==False:
696
- self.contextual_stage_model = None
697
- self.contextual_loss = None
698
- else:
699
- print("ERROR!!!!!self.load_loss should be either True or False!!!")
700
-
701
- def instantiate_cond_stage(self, config):
702
- if not self.cond_stage_trainable:
703
- if config == "__is_first_stage__":
704
- print("Using first stage also as cond stage.")
705
- self.cond_stage_model = self.first_stage_model
706
- elif config == "__is_unconditional__":
707
- print(f"Training {self.__class__.__name__} as an unconditional model.")
708
- self.cond_stage_model = None
709
- # self.be_unconditional = True
710
- else:
711
- model = instantiate_from_config(config)
712
- self.cond_stage_model = model.eval()
713
- self.cond_stage_model.train = disabled_train
714
- for param in self.cond_stage_model.parameters():
715
- param.requires_grad = False
716
- else:
717
- assert config != '__is_first_stage__'
718
- assert config != '__is_unconditional__'
719
- model = instantiate_from_config(config)
720
- self.cond_stage_model = model
721
-
722
- def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
723
- denoise_row = []
724
- for zd in tqdm(samples, desc=desc):
725
- denoise_row.append(self.decode_first_stage(zd.to(self.device),
726
- force_not_quantize=force_no_decoder_quantization))
727
- n_imgs_per_row = len(denoise_row)
728
- denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
729
- denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
730
- denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
731
- denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
732
- return denoise_grid
733
-
734
- def get_first_stage_encoding(self, encoder_posterior):
735
- if isinstance(encoder_posterior, DiagonalGaussianDistribution):
736
- z = encoder_posterior.sample()
737
- elif isinstance(encoder_posterior, torch.Tensor):
738
- z = encoder_posterior
739
- else:
740
- raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
741
- return self.scale_factor * z
742
-
743
- def get_learned_conditioning(self, c):
744
- if self.cond_stage_forward is None:
745
- if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
746
- c = self.cond_stage_model.encode(c)
747
- if isinstance(c, DiagonalGaussianDistribution):
748
- c = c.mode()
749
- else:
750
- c = self.cond_stage_model(c)
751
- else:
752
- assert hasattr(self.cond_stage_model, self.cond_stage_forward)
753
- c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
754
- return c
755
-
756
- def meshgrid(self, h, w):
757
- y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
758
- x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
759
-
760
- arr = torch.cat([y, x], dim=-1)
761
- return arr
762
-
763
- def delta_border(self, h, w):
764
- """
765
- :param h: height
766
- :param w: width
767
- :return: normalized distance to image border,
768
- wtith min distance = 0 at border and max dist = 0.5 at image center
769
- """
770
- lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
771
- arr = self.meshgrid(h, w) / lower_right_corner
772
- dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
773
- dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
774
- edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
775
- return edge_dist
776
-
777
- def get_weighting(self, h, w, Ly, Lx, device):
778
- weighting = self.delta_border(h, w)
779
- weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
780
- self.split_input_params["clip_max_weight"], )
781
- weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
782
-
783
- if self.split_input_params["tie_braker"]:
784
- L_weighting = self.delta_border(Ly, Lx)
785
- L_weighting = torch.clip(L_weighting,
786
- self.split_input_params["clip_min_tie_weight"],
787
- self.split_input_params["clip_max_tie_weight"])
788
-
789
- L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
790
- weighting = weighting * L_weighting
791
- return weighting
792
-
793
- def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
794
- """
795
- :param x: img of size (bs, c, h, w)
796
- :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
797
- """
798
- bs, nc, h, w = x.shape
799
-
800
- # number of crops in image
801
- Ly = (h - kernel_size[0]) // stride[0] + 1
802
- Lx = (w - kernel_size[1]) // stride[1] + 1
803
-
804
- if uf == 1 and df == 1:
805
- fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
806
- unfold = torch.nn.Unfold(**fold_params)
807
-
808
- fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
809
-
810
- weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
811
- normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
812
- weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
813
-
814
- elif uf > 1 and df == 1:
815
- fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
816
- unfold = torch.nn.Unfold(**fold_params)
817
-
818
- fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
819
- dilation=1, padding=0,
820
- stride=(stride[0] * uf, stride[1] * uf))
821
- fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
822
-
823
- weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
824
- normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
825
- weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
826
-
827
- elif df > 1 and uf == 1:
828
- fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
829
- unfold = torch.nn.Unfold(**fold_params)
830
-
831
- fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
832
- dilation=1, padding=0,
833
- stride=(stride[0] // df, stride[1] // df))
834
- fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
835
-
836
- weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
837
- normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
838
- weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
839
-
840
- else:
841
- raise NotImplementedError
842
-
843
- return fold, unfold, normalization, weighting
844
-
845
- @torch.no_grad()
846
- def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
847
- cond_key=None, return_original_cond=False, bs=None, return_x=False):
848
- # print("batch",batch)
849
- # print("k",k)
850
- x = super().get_input(batch, k)
851
- masked_image=batch[self.masked_image]
852
- mask=batch[self.mask]
853
- # print(mask.shape,masked_image.shape)
854
- mask = torch.nn.functional.interpolate(mask, size=(mask.shape[2] // 8, mask.shape[3] // 8))
855
- # mask=torch.cat([mask] * 2) #if do_classifier_free_guidance else mask
856
- mask = mask.to(device="cuda",dtype=x.dtype)
857
- do_classifier_free_guidance=False
858
- # mask, masked_image_latents = self.prepare_mask_latents(
859
- # mask,
860
- # masked_image,
861
- # batch_size * num_images_per_prompt,
862
- # mask.shape[0],
863
- # mask.shape[1],
864
- # mask.dtype,
865
- # "cuda",
866
- # torch.manual_seed(859311133),#generator
867
- # do_classifier_free_guidance,
868
- # )
869
- # print("x",x)
870
- if bs is not None:
871
- x = x[:bs]
872
- x = x.to(self.device)
873
-
874
- encoder_posterior = self.encode_first_stage(x)
875
- z = self.get_first_stage_encoding(encoder_posterior).detach()
876
-
877
- masked_image_latents = self.get_first_stage_encoding(self.encode_first_stage(masked_image)).detach()
878
-
879
- if self.model.conditioning_key is not None and not self.force_null_conditioning:
880
- if cond_key is None:
881
- cond_key = self.cond_stage_key
882
- if cond_key != self.first_stage_key:
883
- if cond_key in ['caption', 'coordinates_bbox', "txt"]:
884
- xc = batch[cond_key]
885
- elif cond_key in ['class_label', 'cls']:
886
- xc = batch
887
- else:
888
- xc = super().get_input(batch, cond_key).to(self.device)
889
- else:
890
- xc = x
891
- if not self.cond_stage_trainable or force_c_encode:
892
- if isinstance(xc, dict) or isinstance(xc, list):
893
- c = self.get_learned_conditioning(xc)
894
- else:
895
- c = self.get_learned_conditioning(xc.to(self.device))
896
- else:
897
- c = xc
898
- if bs is not None:
899
- c = c[:bs]
900
-
901
- if self.use_positional_encodings:
902
- pos_x, pos_y = self.compute_latent_shifts(batch)
903
- ckey = __conditioning_keys__[self.model.conditioning_key]
904
- c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
905
-
906
- else:
907
- c = None
908
- xc = None
909
- if self.use_positional_encodings:
910
- pos_x, pos_y = self.compute_latent_shifts(batch)
911
- c = {'pos_x': pos_x, 'pos_y': pos_y}
912
- out = [z,mask,masked_image_latents, c]
913
- if return_first_stage_outputs:
914
- xrec = self.decode_first_stage(z)
915
- out.extend([x, xrec])
916
- if return_x:
917
- out.extend([x])
918
- if return_original_cond:
919
- out.append(xc)
920
- return out
921
-
922
- @torch.no_grad()
923
- def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
924
- if predict_cids:
925
- if z.dim() == 4:
926
- z = torch.argmax(z.exp(), dim=1).long()
927
- z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
928
- z = rearrange(z, 'b h w c -> b c h w').contiguous()
929
-
930
- z = 1. / self.scale_factor * z
931
- return self.first_stage_model.decode(z)
932
-
933
- @torch.no_grad()
934
- def encode_first_stage(self, x):
935
- return self.first_stage_model.encode(x)
936
-
937
- @torch.no_grad()
938
- def decode_first_stage_before_vae(self, z, predict_cids=False, force_not_quantize=False):
939
- if predict_cids:
940
- if z.dim() == 4:
941
- z = torch.argmax(z.exp(), dim=1).long()
942
- z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
943
- z = rearrange(z, 'b h w c -> b c h w').contiguous()
944
-
945
- z = 1. / self.scale_factor * z
946
- return z
947
-
948
- def shared_step(self, batch, **kwargs):
949
- x,mask,masked_image_latents, c = self.get_input(batch, self.first_stage_key)
950
- loss = self(x,mask,masked_image_latents, c)
951
- return loss
952
-
953
- def forward(self, x,mask,masked_image_latents, c, *args, **kwargs):
954
- t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
955
- if self.model.conditioning_key is not None:
956
- assert c is not None
957
- if self.cond_stage_trainable:
958
- c = self.get_learned_conditioning(c)
959
- if self.shorten_cond_schedule: # TODO: drop this option
960
- tc = self.cond_ids[t].to(self.device)
961
- c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
962
- return self.p_losses(x,mask,masked_image_latents, c, t, *args, **kwargs)
963
-
964
- def apply_model(self, x_noisy, t, cond, return_ids=False):
965
- if isinstance(cond, dict):
966
- # hybrid case, cond is expected to be a dict
967
- pass
968
- else:
969
- if not isinstance(cond, list):
970
- cond = [cond]
971
- key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
972
- cond = {key: cond}
973
-
974
- x_recon = self.model(x_noisy, t, **cond)
975
-
976
- if isinstance(x_recon, tuple) and not return_ids:
977
- return x_recon[0]
978
- else:
979
- return x_recon
980
-
981
- def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
982
- return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
983
- extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
984
-
985
- def _prior_bpd(self, x_start):
986
- """
987
- Get the prior KL term for the variational lower-bound, measured in
988
- bits-per-dim.
989
- This term can't be optimized, as it only depends on the encoder.
990
- :param x_start: the [N x C x ...] tensor of inputs.
991
- :return: a batch of [N] KL values (in bits), one per batch element.
992
- """
993
- batch_size = x_start.shape[0]
994
- t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
995
- qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
996
- kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
997
- return mean_flat(kl_prior) / np.log(2.0)
998
-
999
- def p_losses(self, x_start,mask,masked_image_latents, cond, t, noise=None): #latent diffusion
1000
- noise = default(noise, lambda: torch.randn_like(x_start))
1001
- x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
1002
- model_output = self.apply_model(x_noisy,mask,masked_image_latents, t, cond)
1003
- # print("before loss: ", model_output.shape)
1004
- loss_dict = {}
1005
- prefix = 'train' if self.training else 'val'
1006
-
1007
- if self.parameterization == "x0":
1008
- target = x_start
1009
- elif self.parameterization == "eps":
1010
- target = noise
1011
- elif self.parameterization == "v":
1012
- target = self.get_v(x_start, noise, t)
1013
- else:
1014
- raise NotImplementedError()
1015
-
1016
- loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
1017
- loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
1018
-
1019
- logvar_t = self.logvar[t].to(self.device)
1020
- loss = loss_simple / torch.exp(logvar_t) + logvar_t
1021
- # loss = loss_simple / torch.exp(self.logvar) + self.logvar
1022
- if self.learn_logvar:
1023
- loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
1024
- loss_dict.update({'logvar': self.logvar.data.mean()})
1025
-
1026
- loss = self.l_simple_weight * loss.mean()
1027
-
1028
- loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
1029
- loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
1030
- loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
1031
- loss += (self.original_elbo_weight * loss_vlb)
1032
- loss_dict.update({f'{prefix}/loss': loss})
1033
-
1034
- return loss, loss_dict
1035
-
1036
- def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
1037
- return_x0=False, score_corrector=None, corrector_kwargs=None):
1038
- t_in = t
1039
- model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
1040
-
1041
- if score_corrector is not None:
1042
- assert self.parameterization == "eps"
1043
- model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
1044
-
1045
- if return_codebook_ids:
1046
- model_out, logits = model_out
1047
-
1048
- if self.parameterization == "eps":
1049
- x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
1050
- elif self.parameterization == "x0":
1051
- x_recon = model_out
1052
- else:
1053
- raise NotImplementedError()
1054
-
1055
- if clip_denoised:
1056
- x_recon.clamp_(-1., 1.)
1057
- if quantize_denoised:
1058
- x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
1059
- model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
1060
- if return_codebook_ids:
1061
- return model_mean, posterior_variance, posterior_log_variance, logits
1062
- elif return_x0:
1063
- return model_mean, posterior_variance, posterior_log_variance, x_recon
1064
- else:
1065
- return model_mean, posterior_variance, posterior_log_variance
1066
-
1067
- @torch.no_grad()
1068
- def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
1069
- return_codebook_ids=False, quantize_denoised=False, return_x0=False,
1070
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
1071
- b, *_, device = *x.shape, x.device
1072
- outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
1073
- return_codebook_ids=return_codebook_ids,
1074
- quantize_denoised=quantize_denoised,
1075
- return_x0=return_x0,
1076
- score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1077
- if return_codebook_ids:
1078
- raise DeprecationWarning("Support dropped.")
1079
- model_mean, _, model_log_variance, logits = outputs
1080
- elif return_x0:
1081
- model_mean, _, model_log_variance, x0 = outputs
1082
- else:
1083
- model_mean, _, model_log_variance = outputs
1084
-
1085
- noise = noise_like(x.shape, device, repeat_noise) * temperature
1086
- if noise_dropout > 0.:
1087
- noise = torch.nn.functional.dropout(noise, p=noise_dropout)
1088
- # no noise when t == 0
1089
- nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
1090
-
1091
- if return_codebook_ids:
1092
- return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
1093
- if return_x0:
1094
- return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
1095
- else:
1096
- return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
1097
-
1098
- @torch.no_grad()
1099
- def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
1100
- img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
1101
- score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
1102
- log_every_t=None):
1103
- if not log_every_t:
1104
- log_every_t = self.log_every_t
1105
- timesteps = self.num_timesteps
1106
- if batch_size is not None:
1107
- b = batch_size if batch_size is not None else shape[0]
1108
- shape = [batch_size] + list(shape)
1109
- else:
1110
- b = batch_size = shape[0]
1111
- if x_T is None:
1112
- img = torch.randn(shape, device=self.device)
1113
- else:
1114
- img = x_T
1115
- intermediates = []
1116
- if cond is not None:
1117
- if isinstance(cond, dict):
1118
- cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1119
- list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1120
- else:
1121
- cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1122
-
1123
- if start_T is not None:
1124
- timesteps = min(timesteps, start_T)
1125
- iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
1126
- total=timesteps) if verbose else reversed(
1127
- range(0, timesteps))
1128
- if type(temperature) == float:
1129
- temperature = [temperature] * timesteps
1130
-
1131
- for i in iterator:
1132
- ts = torch.full((b,), i, device=self.device, dtype=torch.long)
1133
- if self.shorten_cond_schedule:
1134
- assert self.model.conditioning_key != 'hybrid'
1135
- tc = self.cond_ids[ts].to(cond.device)
1136
- cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1137
-
1138
- img, x0_partial = self.p_sample(img, cond, ts,
1139
- clip_denoised=self.clip_denoised,
1140
- quantize_denoised=quantize_denoised, return_x0=True,
1141
- temperature=temperature[i], noise_dropout=noise_dropout,
1142
- score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1143
- if mask is not None:
1144
- assert x0 is not None
1145
- img_orig = self.q_sample(x0, ts)
1146
- img = img_orig * mask + (1. - mask) * img
1147
-
1148
- if i % log_every_t == 0 or i == timesteps - 1:
1149
- intermediates.append(x0_partial)
1150
- if callback: callback(i)
1151
- if img_callback: img_callback(img, i)
1152
- return img, intermediates
1153
-
1154
- @torch.no_grad()
1155
- def p_sample_loop(self, cond, shape, return_intermediates=False,
1156
- x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
1157
- mask=None, x0=None, img_callback=None, start_T=None,
1158
- log_every_t=None):
1159
-
1160
- if not log_every_t:
1161
- log_every_t = self.log_every_t
1162
- device = self.betas.device
1163
- b = shape[0]
1164
- if x_T is None:
1165
- img = torch.randn(shape, device=device)
1166
- else:
1167
- img = x_T
1168
-
1169
- intermediates = [img]
1170
- if timesteps is None:
1171
- timesteps = self.num_timesteps
1172
-
1173
- if start_T is not None:
1174
- timesteps = min(timesteps, start_T)
1175
- iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
1176
- range(0, timesteps))
1177
-
1178
- if mask is not None:
1179
- assert x0 is not None
1180
- assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
1181
-
1182
- for i in iterator:
1183
- ts = torch.full((b,), i, device=device, dtype=torch.long)
1184
- if self.shorten_cond_schedule:
1185
- assert self.model.conditioning_key != 'hybrid'
1186
- tc = self.cond_ids[ts].to(cond.device)
1187
- cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1188
-
1189
- img = self.p_sample(img, cond, ts,
1190
- clip_denoised=self.clip_denoised,
1191
- quantize_denoised=quantize_denoised)
1192
- if mask is not None:
1193
- img_orig = self.q_sample(x0, ts)
1194
- img = img_orig * mask + (1. - mask) * img
1195
-
1196
- if i % log_every_t == 0 or i == timesteps - 1:
1197
- intermediates.append(img)
1198
- if callback: callback(i)
1199
- if img_callback: img_callback(img, i)
1200
-
1201
- if return_intermediates:
1202
- return img, intermediates
1203
- return img
1204
-
1205
- @torch.no_grad()
1206
- def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
1207
- verbose=True, timesteps=None, quantize_denoised=False,
1208
- mask=None, x0=None, shape=None, **kwargs):
1209
- if shape is None:
1210
- shape = (batch_size, self.channels, self.image_size, self.image_size)
1211
- if cond is not None:
1212
- if isinstance(cond, dict):
1213
- cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1214
- list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1215
- else:
1216
- cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1217
- return self.p_sample_loop(cond,
1218
- shape,
1219
- return_intermediates=return_intermediates, x_T=x_T,
1220
- verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
1221
- mask=mask, x0=x0)
1222
-
1223
- @torch.no_grad()
1224
- def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
1225
- if ddim:
1226
- ddim_sampler = DDIMSampler(self)
1227
- shape = (self.channels, self.image_size, self.image_size)
1228
- samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size,
1229
- shape, cond, verbose=False, **kwargs)
1230
-
1231
- else:
1232
- samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
1233
- return_intermediates=True, **kwargs)
1234
-
1235
- return samples, intermediates
1236
-
1237
- @torch.no_grad()
1238
- def get_unconditional_conditioning(self, batch_size, null_label=None):
1239
- if null_label is not None:
1240
- xc = null_label
1241
- if isinstance(xc, ListConfig):
1242
- xc = list(xc)
1243
- if isinstance(xc, dict) or isinstance(xc, list):
1244
- c = self.get_learned_conditioning(xc)
1245
- else:
1246
- if hasattr(xc, "to"):
1247
- xc = xc.to(self.device)
1248
- c = self.get_learned_conditioning(xc)
1249
- else:
1250
- if self.cond_stage_key in ["class_label", "cls"]:
1251
- xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device)
1252
- return self.get_learned_conditioning(xc)
1253
- else:
1254
- raise NotImplementedError("todo")
1255
- if isinstance(c, list): # in case the encoder gives us a list
1256
- for i in range(len(c)):
1257
- c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device)
1258
- else:
1259
- c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device)
1260
- return c
1261
-
1262
- @torch.no_grad()
1263
- def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None,
1264
- quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
1265
- plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
1266
- use_ema_scope=True,
1267
- **kwargs):
1268
- ema_scope = self.ema_scope if use_ema_scope else nullcontext
1269
- use_ddim = ddim_steps is not None
1270
-
1271
- log = dict()
1272
- z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
1273
- return_first_stage_outputs=True,
1274
- force_c_encode=True,
1275
- return_original_cond=True,
1276
- bs=N)
1277
- N = min(x.shape[0], N)
1278
- n_row = min(x.shape[0], n_row)
1279
- log["inputs"] = x
1280
- log["reconstruction"] = xrec
1281
- if self.model.conditioning_key is not None:
1282
- if hasattr(self.cond_stage_model, "decode"):
1283
- xc = self.cond_stage_model.decode(c)
1284
- log["conditioning"] = xc
1285
- elif self.cond_stage_key in ["caption", "txt"]:
1286
- xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
1287
- log["conditioning"] = xc
1288
- elif self.cond_stage_key in ['class_label', "cls"]:
1289
- try:
1290
- xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
1291
- log['conditioning'] = xc
1292
- except KeyError:
1293
- # probably no "human_label" in batch
1294
- pass
1295
- elif isimage(xc):
1296
- log["conditioning"] = xc
1297
- if ismap(xc):
1298
- log["original_conditioning"] = self.to_rgb(xc)
1299
-
1300
- if plot_diffusion_rows:
1301
- # get diffusion row
1302
- diffusion_row = list()
1303
- z_start = z[:n_row]
1304
- for t in range(self.num_timesteps):
1305
- if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1306
- t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1307
- t = t.to(self.device).long()
1308
- noise = torch.randn_like(z_start)
1309
- z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1310
- diffusion_row.append(self.decode_first_stage(z_noisy))
1311
-
1312
- diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1313
- diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1314
- diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1315
- diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1316
- log["diffusion_row"] = diffusion_grid
1317
-
1318
- if sample:
1319
- # get denoise row
1320
- with ema_scope("Sampling"):
1321
- samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
1322
- ddim_steps=ddim_steps, eta=ddim_eta)
1323
- # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1324
- x_samples = self.decode_first_stage(samples)
1325
- log["samples"] = x_samples
1326
- if plot_denoise_rows:
1327
- denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1328
- log["denoise_row"] = denoise_grid
1329
-
1330
- if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
1331
- self.first_stage_model, IdentityFirstStage):
1332
- # also display when quantizing x0 while sampling
1333
- with ema_scope("Plotting Quantized Denoised"):
1334
- samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
1335
- ddim_steps=ddim_steps, eta=ddim_eta,
1336
- quantize_denoised=True)
1337
- # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
1338
- # quantize_denoised=True)
1339
- x_samples = self.decode_first_stage(samples.to(self.device))
1340
- log["samples_x0_quantized"] = x_samples
1341
-
1342
- if unconditional_guidance_scale > 1.0:
1343
- uc = self.get_unconditional_conditioning(N, unconditional_guidance_label)
1344
- if self.model.conditioning_key == "crossattn-adm":
1345
- uc = {"c_crossattn": [uc], "c_adm": c["c_adm"]}
1346
- with ema_scope("Sampling with classifier-free guidance"):
1347
- samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
1348
- ddim_steps=ddim_steps, eta=ddim_eta,
1349
- unconditional_guidance_scale=unconditional_guidance_scale,
1350
- unconditional_conditioning=uc,
1351
- )
1352
- x_samples_cfg = self.decode_first_stage(samples_cfg)
1353
- log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
1354
-
1355
- if inpaint:
1356
- # make a simple center square
1357
- b, h, w = z.shape[0], z.shape[2], z.shape[3]
1358
- mask = torch.ones(N, h, w).to(self.device)
1359
- # zeros will be filled in
1360
- mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
1361
- mask = mask[:, None, ...]
1362
- with ema_scope("Plotting Inpaint"):
1363
- samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,
1364
- ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1365
- x_samples = self.decode_first_stage(samples.to(self.device))
1366
- log["samples_inpainting"] = x_samples
1367
- log["mask"] = mask
1368
-
1369
- # outpaint
1370
- mask = 1. - mask
1371
- with ema_scope("Plotting Outpaint"):
1372
- samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,
1373
- ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1374
- x_samples = self.decode_first_stage(samples.to(self.device))
1375
- log["samples_outpainting"] = x_samples
1376
-
1377
- if plot_progressive_rows:
1378
- with ema_scope("Plotting Progressives"):
1379
- img, progressives = self.progressive_denoising(c,
1380
- shape=(self.channels, self.image_size, self.image_size),
1381
- batch_size=N)
1382
- prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
1383
- log["progressive_row"] = prog_row
1384
-
1385
- if return_keys:
1386
- if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
1387
- return log
1388
- else:
1389
- return {key: log[key] for key in return_keys}
1390
- return log
1391
-
1392
- def configure_optimizers(self):
1393
- lr = self.learning_rate
1394
- params = list(self.model.parameters())
1395
- if self.cond_stage_trainable:
1396
- print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
1397
- params = params + list(self.cond_stage_model.parameters())
1398
- if self.learn_logvar:
1399
- print('Diffusion model optimizing logvar')
1400
- params.append(self.logvar)
1401
- opt = torch.optim.AdamW(params, lr=lr)
1402
- if self.use_scheduler:
1403
- assert 'target' in self.scheduler_config
1404
- scheduler = instantiate_from_config(self.scheduler_config)
1405
-
1406
- print("Setting up LambdaLR scheduler...")
1407
- scheduler = [
1408
- {
1409
- 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
1410
- 'interval': 'step',
1411
- 'frequency': 1
1412
- }]
1413
- return [opt], scheduler
1414
- return opt
1415
-
1416
- @torch.no_grad()
1417
- def to_rgb(self, x):
1418
- x = x.float()
1419
- if not hasattr(self, "colorize"):
1420
- self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
1421
- x = nn.functional.conv2d(x, weight=self.colorize)
1422
- x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
1423
- return x
1424
-
1425
-
1426
- class DiffusionWrapper(pl.LightningModule):
1427
- def __init__(self, diff_model_config, conditioning_key):
1428
- super().__init__()
1429
- self.sequential_cross_attn = diff_model_config.pop("sequential_crossattn", False)
1430
- self.diffusion_model = instantiate_from_config(diff_model_config)
1431
- self.conditioning_key = conditioning_key
1432
- assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm', 'hybrid-adm', 'crossattn-adm']
1433
-
1434
- def forward(self, x, t, c_concat: list = None, c_crossattn: list = None, c_adm=None):
1435
- if self.conditioning_key is None:
1436
- out = self.diffusion_model(x, t)
1437
- elif self.conditioning_key == 'concat':
1438
- xc = torch.cat([x] + c_concat, dim=1)
1439
- out = self.diffusion_model(xc, t)
1440
- elif self.conditioning_key == 'crossattn':
1441
- if not self.sequential_cross_attn:
1442
- cc = torch.cat(c_crossattn, 1)
1443
- else:
1444
- cc = c_crossattn
1445
- out = self.diffusion_model(x, t, context=cc)
1446
- elif self.conditioning_key == 'hybrid':
1447
- xc = torch.cat([x] + c_concat, dim=1)
1448
- cc = torch.cat(c_crossattn, 1)
1449
- out = self.diffusion_model(xc, t, context=cc)
1450
- elif self.conditioning_key == 'hybrid-adm':
1451
- assert c_adm is not None
1452
- xc = torch.cat([x] + c_concat, dim=1)
1453
- cc = torch.cat(c_crossattn, 1)
1454
- out = self.diffusion_model(xc, t, context=cc, y=c_adm)
1455
- elif self.conditioning_key == 'crossattn-adm':
1456
- assert c_adm is not None
1457
- cc = torch.cat(c_crossattn, 1)
1458
- out = self.diffusion_model(x, t, context=cc, y=c_adm)
1459
- elif self.conditioning_key == 'adm':
1460
- cc = c_crossattn[0]
1461
- out = self.diffusion_model(x, t, y=cc)
1462
- else:
1463
- raise NotImplementedError()
1464
-
1465
- return out
1466
-
1467
-
1468
- class LatentUpscaleDiffusion(LatentDiffusion):
1469
- def __init__(self, *args, low_scale_config, low_scale_key="LR", noise_level_key=None, **kwargs):
1470
- super().__init__(*args, **kwargs)
1471
- # assumes that neither the cond_stage nor the low_scale_model contain trainable params
1472
- assert not self.cond_stage_trainable
1473
- self.instantiate_low_stage(low_scale_config)
1474
- self.low_scale_key = low_scale_key
1475
- self.noise_level_key = noise_level_key
1476
-
1477
- def instantiate_low_stage(self, config):
1478
- model = instantiate_from_config(config)
1479
- self.low_scale_model = model.eval()
1480
- self.low_scale_model.train = disabled_train
1481
- for param in self.low_scale_model.parameters():
1482
- param.requires_grad = False
1483
-
1484
- @torch.no_grad()
1485
- def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False):
1486
- if not log_mode:
1487
- z, c = super().get_input(batch, k, force_c_encode=True, bs=bs)
1488
- else:
1489
- z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
1490
- force_c_encode=True, return_original_cond=True, bs=bs)
1491
- x_low = batch[self.low_scale_key][:bs]
1492
- x_low = rearrange(x_low, 'b h w c -> b c h w')
1493
- x_low = x_low.to(memory_format=torch.contiguous_format).float()
1494
- zx, noise_level = self.low_scale_model(x_low)
1495
- if self.noise_level_key is not None:
1496
- # get noise level from batch instead, e.g. when extracting a custom noise level for bsr
1497
- raise NotImplementedError('TODO')
1498
-
1499
- all_conds = {"c_concat": [zx], "c_crossattn": [c], "c_adm": noise_level}
1500
- if log_mode:
1501
- # TODO: maybe disable if too expensive
1502
- x_low_rec = self.low_scale_model.decode(zx)
1503
- return z, all_conds, x, xrec, xc, x_low, x_low_rec, noise_level
1504
- return z, all_conds
1505
-
1506
- @torch.no_grad()
1507
- def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
1508
- plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True,
1509
- unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True,
1510
- **kwargs):
1511
- ema_scope = self.ema_scope if use_ema_scope else nullcontext
1512
- use_ddim = ddim_steps is not None
1513
-
1514
- log = dict()
1515
- z, c, x, xrec, xc, x_low, x_low_rec, noise_level = self.get_input(batch, self.first_stage_key, bs=N,
1516
- log_mode=True)
1517
- N = min(x.shape[0], N)
1518
- n_row = min(x.shape[0], n_row)
1519
- log["inputs"] = x
1520
- log["reconstruction"] = xrec
1521
- log["x_lr"] = x_low
1522
- log[f"x_lr_rec_@noise_levels{'-'.join(map(lambda x: str(x), list(noise_level.cpu().numpy())))}"] = x_low_rec
1523
- if self.model.conditioning_key is not None:
1524
- if hasattr(self.cond_stage_model, "decode"):
1525
- xc = self.cond_stage_model.decode(c)
1526
- log["conditioning"] = xc
1527
- elif self.cond_stage_key in ["caption", "txt"]:
1528
- xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
1529
- log["conditioning"] = xc
1530
- elif self.cond_stage_key in ['class_label', 'cls']:
1531
- xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
1532
- log['conditioning'] = xc
1533
- elif isimage(xc):
1534
- log["conditioning"] = xc
1535
- if ismap(xc):
1536
- log["original_conditioning"] = self.to_rgb(xc)
1537
-
1538
- if plot_diffusion_rows:
1539
- # get diffusion row
1540
- diffusion_row = list()
1541
- z_start = z[:n_row]
1542
- for t in range(self.num_timesteps):
1543
- if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1544
- t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1545
- t = t.to(self.device).long()
1546
- noise = torch.randn_like(z_start)
1547
- z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1548
- diffusion_row.append(self.decode_first_stage(z_noisy))
1549
-
1550
- diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1551
- diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1552
- diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1553
- diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1554
- log["diffusion_row"] = diffusion_grid
1555
-
1556
- if sample:
1557
- # get denoise row
1558
- with ema_scope("Sampling"):
1559
- samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
1560
- ddim_steps=ddim_steps, eta=ddim_eta)
1561
- # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1562
- x_samples = self.decode_first_stage(samples)
1563
- log["samples"] = x_samples
1564
- if plot_denoise_rows:
1565
- denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1566
- log["denoise_row"] = denoise_grid
1567
-
1568
- if unconditional_guidance_scale > 1.0:
1569
- uc_tmp = self.get_unconditional_conditioning(N, unconditional_guidance_label)
1570
- # TODO explore better "unconditional" choices for the other keys
1571
- # maybe guide away from empty text label and highest noise level and maximally degraded zx?
1572
- uc = dict()
1573
- for k in c:
1574
- if k == "c_crossattn":
1575
- assert isinstance(c[k], list) and len(c[k]) == 1
1576
- uc[k] = [uc_tmp]
1577
- elif k == "c_adm": # todo: only run with text-based guidance?
1578
- assert isinstance(c[k], torch.Tensor)
1579
- #uc[k] = torch.ones_like(c[k]) * self.low_scale_model.max_noise_level
1580
- uc[k] = c[k]
1581
- elif isinstance(c[k], list):
1582
- uc[k] = [c[k][i] for i in range(len(c[k]))]
1583
- else:
1584
- uc[k] = c[k]
1585
-
1586
- with ema_scope("Sampling with classifier-free guidance"):
1587
- samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
1588
- ddim_steps=ddim_steps, eta=ddim_eta,
1589
- unconditional_guidance_scale=unconditional_guidance_scale,
1590
- unconditional_conditioning=uc,
1591
- )
1592
- x_samples_cfg = self.decode_first_stage(samples_cfg)
1593
- log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
1594
-
1595
- if plot_progressive_rows:
1596
- with ema_scope("Plotting Progressives"):
1597
- img, progressives = self.progressive_denoising(c,
1598
- shape=(self.channels, self.image_size, self.image_size),
1599
- batch_size=N)
1600
- prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
1601
- log["progressive_row"] = prog_row
1602
-
1603
- return log
1604
-
1605
-
1606
- class LatentFinetuneDiffusion(LatentDiffusion):
1607
- """
1608
- Basis for different finetunas, such as inpainting or depth2image
1609
- To disable finetuning mode, set finetune_keys to None
1610
- """
1611
-
1612
- def __init__(self,
1613
- concat_keys: tuple,
1614
- finetune_keys=("model.diffusion_model.input_blocks.0.0.weight",
1615
- "model_ema.diffusion_modelinput_blocks00weight"
1616
- ),
1617
- keep_finetune_dims=4,
1618
- # if model was trained without concat mode before and we would like to keep these channels
1619
- c_concat_log_start=None, # to log reconstruction of c_concat codes
1620
- c_concat_log_end=None,
1621
- *args, **kwargs
1622
- ):
1623
- ckpt_path = kwargs.pop("ckpt_path", None)
1624
- ignore_keys = kwargs.pop("ignore_keys", list())
1625
- super().__init__(*args, **kwargs)
1626
- self.finetune_keys = finetune_keys
1627
- self.concat_keys = concat_keys
1628
- self.keep_dims = keep_finetune_dims
1629
- self.c_concat_log_start = c_concat_log_start
1630
- self.c_concat_log_end = c_concat_log_end
1631
- if exists(self.finetune_keys): assert exists(ckpt_path), 'can only finetune from a given checkpoint'
1632
- if exists(ckpt_path):
1633
- self.init_from_ckpt(ckpt_path, ignore_keys)
1634
-
1635
- def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
1636
- sd = torch.load(path, map_location="cpu")
1637
- if "state_dict" in list(sd.keys()):
1638
- sd = sd["state_dict"]
1639
- keys = list(sd.keys())
1640
- for k in keys:
1641
- for ik in ignore_keys:
1642
- if k.startswith(ik):
1643
- print("Deleting key {} from state_dict.".format(k))
1644
- del sd[k]
1645
-
1646
- # make it explicit, finetune by including extra input channels
1647
- if exists(self.finetune_keys) and k in self.finetune_keys:
1648
- new_entry = None
1649
- for name, param in self.named_parameters():
1650
- if name in self.finetune_keys:
1651
- print(
1652
- f"modifying key '{name}' and keeping its original {self.keep_dims} (channels) dimensions only")
1653
- new_entry = torch.zeros_like(param) # zero init
1654
- assert exists(new_entry), 'did not find matching parameter to modify'
1655
- new_entry[:, :self.keep_dims, ...] = sd[k]
1656
- sd[k] = new_entry
1657
-
1658
- missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
1659
- sd, strict=False)
1660
- print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
1661
- if len(missing) > 0:
1662
- print(f"Missing Keys: {missing}")
1663
- if len(unexpected) > 0:
1664
- print(f"Unexpected Keys: {unexpected}")
1665
-
1666
- @torch.no_grad()
1667
- def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
1668
- quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
1669
- plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
1670
- use_ema_scope=True,
1671
- **kwargs):
1672
- ema_scope = self.ema_scope if use_ema_scope else nullcontext
1673
- use_ddim = ddim_steps is not None
1674
-
1675
- log = dict()
1676
- z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, bs=N, return_first_stage_outputs=True)
1677
- c_cat, c = c["c_concat"][0], c["c_crossattn"][0]
1678
- N = min(x.shape[0], N)
1679
- n_row = min(x.shape[0], n_row)
1680
- log["inputs"] = x
1681
- log["reconstruction"] = xrec
1682
- if self.model.conditioning_key is not None:
1683
- if hasattr(self.cond_stage_model, "decode"):
1684
- xc = self.cond_stage_model.decode(c)
1685
- log["conditioning"] = xc
1686
- elif self.cond_stage_key in ["caption", "txt"]:
1687
- xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
1688
- log["conditioning"] = xc
1689
- elif self.cond_stage_key in ['class_label', 'cls']:
1690
- xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
1691
- log['conditioning'] = xc
1692
- elif isimage(xc):
1693
- log["conditioning"] = xc
1694
- if ismap(xc):
1695
- log["original_conditioning"] = self.to_rgb(xc)
1696
-
1697
- if not (self.c_concat_log_start is None and self.c_concat_log_end is None):
1698
- log["c_concat_decoded"] = self.decode_first_stage(c_cat[:, self.c_concat_log_start:self.c_concat_log_end])
1699
-
1700
- if plot_diffusion_rows:
1701
- # get diffusion row
1702
- diffusion_row = list()
1703
- z_start = z[:n_row]
1704
- for t in range(self.num_timesteps):
1705
- if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1706
- t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1707
- t = t.to(self.device).long()
1708
- noise = torch.randn_like(z_start)
1709
- z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1710
- diffusion_row.append(self.decode_first_stage(z_noisy))
1711
-
1712
- diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1713
- diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1714
- diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1715
- diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1716
- log["diffusion_row"] = diffusion_grid
1717
-
1718
- if sample:
1719
- # get denoise row
1720
- with ema_scope("Sampling"):
1721
- samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
1722
- batch_size=N, ddim=use_ddim,
1723
- ddim_steps=ddim_steps, eta=ddim_eta)
1724
- # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1725
- x_samples = self.decode_first_stage(samples)
1726
- log["samples"] = x_samples
1727
- if plot_denoise_rows:
1728
- denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1729
- log["denoise_row"] = denoise_grid
1730
-
1731
- if unconditional_guidance_scale > 1.0:
1732
- uc_cross = self.get_unconditional_conditioning(N, unconditional_guidance_label)
1733
- uc_cat = c_cat
1734
- uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]}
1735
- with ema_scope("Sampling with classifier-free guidance"):
1736
- samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
1737
- batch_size=N, ddim=use_ddim,
1738
- ddim_steps=ddim_steps, eta=ddim_eta,
1739
- unconditional_guidance_scale=unconditional_guidance_scale,
1740
- unconditional_conditioning=uc_full,
1741
- )
1742
- x_samples_cfg = self.decode_first_stage(samples_cfg)
1743
- log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
1744
-
1745
- return log
1746
-
1747
-
1748
- class LatentInpaintDiffusion(LatentFinetuneDiffusion):
1749
- """
1750
- can either run as pure inpainting model (only concat mode) or with mixed conditionings,
1751
- e.g. mask as concat and text via cross-attn.
1752
- To disable finetuning mode, set finetune_keys to None
1753
- """
1754
-
1755
- def __init__(self,
1756
- concat_keys=("mask", "masked_image"),
1757
- masked_image_key="masked_image",
1758
- *args, **kwargs
1759
- ):
1760
- super().__init__(concat_keys, *args, **kwargs)
1761
- self.masked_image_key = masked_image_key
1762
- assert self.masked_image_key in concat_keys
1763
-
1764
- @torch.no_grad()
1765
- def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
1766
- # note: restricted to non-trainable encoders currently
1767
- assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for inpainting'
1768
- z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
1769
- force_c_encode=True, return_original_cond=True, bs=bs)
1770
-
1771
- assert exists(self.concat_keys)
1772
- c_cat = list()
1773
- for ck in self.concat_keys:
1774
- cc = rearrange(batch[ck], 'b h w c -> b c h w').to(memory_format=torch.contiguous_format).float()
1775
- if bs is not None:
1776
- cc = cc[:bs]
1777
- cc = cc.to(self.device)
1778
- bchw = z.shape
1779
- if ck != self.masked_image_key:
1780
- cc = torch.nn.functional.interpolate(cc, size=bchw[-2:])
1781
- else:
1782
- cc = self.get_first_stage_encoding(self.encode_first_stage(cc))
1783
- c_cat.append(cc)
1784
- c_cat = torch.cat(c_cat, dim=1)
1785
- all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
1786
- if return_first_stage_outputs:
1787
- return z, all_conds, x, xrec, xc
1788
- return z, all_conds
1789
-
1790
- @torch.no_grad()
1791
- def log_images(self, *args, **kwargs):
1792
- log = super(LatentInpaintDiffusion, self).log_images(*args, **kwargs)
1793
- log["masked_image"] = rearrange(args[0]["masked_image"],
1794
- 'b h w c -> b c h w').to(memory_format=torch.contiguous_format).float()
1795
- return log
1796
-
1797
-
1798
- class LatentDepth2ImageDiffusion(LatentFinetuneDiffusion):
1799
- """
1800
- condition on monocular depth estimation
1801
- """
1802
-
1803
- def __init__(self, depth_stage_config, concat_keys=("midas_in",), *args, **kwargs):
1804
- super().__init__(concat_keys=concat_keys, *args, **kwargs)
1805
- self.depth_model = instantiate_from_config(depth_stage_config)
1806
- self.depth_stage_key = concat_keys[0]
1807
-
1808
- @torch.no_grad()
1809
- def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
1810
- # note: restricted to non-trainable encoders currently
1811
- assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for depth2img'
1812
- z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
1813
- force_c_encode=True, return_original_cond=True, bs=bs)
1814
-
1815
- assert exists(self.concat_keys)
1816
- assert len(self.concat_keys) == 1
1817
- c_cat = list()
1818
- for ck in self.concat_keys:
1819
- cc = batch[ck]
1820
- if bs is not None:
1821
- cc = cc[:bs]
1822
- cc = cc.to(self.device)
1823
- cc = self.depth_model(cc)
1824
- cc = torch.nn.functional.interpolate(
1825
- cc,
1826
- size=z.shape[2:],
1827
- mode="bicubic",
1828
- align_corners=False,
1829
- )
1830
-
1831
- depth_min, depth_max = torch.amin(cc, dim=[1, 2, 3], keepdim=True), torch.amax(cc, dim=[1, 2, 3],
1832
- keepdim=True)
1833
- cc = 2. * (cc - depth_min) / (depth_max - depth_min + 0.001) - 1.
1834
- c_cat.append(cc)
1835
- c_cat = torch.cat(c_cat, dim=1)
1836
- all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
1837
- if return_first_stage_outputs:
1838
- return z, all_conds, x, xrec, xc
1839
- return z, all_conds
1840
-
1841
- @torch.no_grad()
1842
- def log_images(self, *args, **kwargs):
1843
- log = super().log_images(*args, **kwargs)
1844
- depth = self.depth_model(args[0][self.depth_stage_key])
1845
- depth_min, depth_max = torch.amin(depth, dim=[1, 2, 3], keepdim=True), \
1846
- torch.amax(depth, dim=[1, 2, 3], keepdim=True)
1847
- log["depth"] = 2. * (depth - depth_min) / (depth_max - depth_min) - 1.
1848
- return log
1849
-
1850
-
1851
- class LatentUpscaleFinetuneDiffusion(LatentFinetuneDiffusion):
1852
- """
1853
- condition on low-res image (and optionally on some spatial noise augmentation)
1854
- """
1855
- def __init__(self, concat_keys=("lr",), reshuffle_patch_size=None,
1856
- low_scale_config=None, low_scale_key=None, *args, **kwargs):
1857
- super().__init__(concat_keys=concat_keys, *args, **kwargs)
1858
- self.reshuffle_patch_size = reshuffle_patch_size
1859
- self.low_scale_model = None
1860
- if low_scale_config is not None:
1861
- print("Initializing a low-scale model")
1862
- assert exists(low_scale_key)
1863
- self.instantiate_low_stage(low_scale_config)
1864
- self.low_scale_key = low_scale_key
1865
-
1866
- def instantiate_low_stage(self, config):
1867
- model = instantiate_from_config(config)
1868
- self.low_scale_model = model.eval()
1869
- self.low_scale_model.train = disabled_train
1870
- for param in self.low_scale_model.parameters():
1871
- param.requires_grad = False
1872
-
1873
- @torch.no_grad()
1874
- def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
1875
- # note: restricted to non-trainable encoders currently
1876
- assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for upscaling-ft'
1877
- z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
1878
- force_c_encode=True, return_original_cond=True, bs=bs)
1879
-
1880
- assert exists(self.concat_keys)
1881
- assert len(self.concat_keys) == 1
1882
- # optionally make spatial noise_level here
1883
- c_cat = list()
1884
- noise_level = None
1885
- for ck in self.concat_keys:
1886
- cc = batch[ck]
1887
- cc = rearrange(cc, 'b h w c -> b c h w')
1888
- if exists(self.reshuffle_patch_size):
1889
- assert isinstance(self.reshuffle_patch_size, int)
1890
- cc = rearrange(cc, 'b c (p1 h) (p2 w) -> b (p1 p2 c) h w',
1891
- p1=self.reshuffle_patch_size, p2=self.reshuffle_patch_size)
1892
- if bs is not None:
1893
- cc = cc[:bs]
1894
- cc = cc.to(self.device)
1895
- if exists(self.low_scale_model) and ck == self.low_scale_key:
1896
- cc, noise_level = self.low_scale_model(cc)
1897
- c_cat.append(cc)
1898
- c_cat = torch.cat(c_cat, dim=1)
1899
- if exists(noise_level):
1900
- all_conds = {"c_concat": [c_cat], "c_crossattn": [c], "c_adm": noise_level}
1901
- else:
1902
- all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
1903
- if return_first_stage_outputs:
1904
- return z, all_conds, x, xrec, xc
1905
- return z, all_conds
1906
-
1907
- @torch.no_grad()
1908
- def log_images(self, *args, **kwargs):
1909
- log = super().log_images(*args, **kwargs)
1910
- log["lr"] = rearrange(args[0]["lr"], 'b h w c -> b c h w')
1911
- return log
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/models/diffusion/dpm_solver/__init__.py DELETED
@@ -1 +0,0 @@
1
- from .sampler import DPMSolverSampler
 
 
Control-Color/ldm/models/diffusion/dpm_solver/dpm_solver.py DELETED
@@ -1,1154 +0,0 @@
1
- import torch
2
- import torch.nn.functional as F
3
- import math
4
- from tqdm import tqdm
5
-
6
-
7
- class NoiseScheduleVP:
8
- def __init__(
9
- self,
10
- schedule='discrete',
11
- betas=None,
12
- alphas_cumprod=None,
13
- continuous_beta_0=0.1,
14
- continuous_beta_1=20.,
15
- ):
16
- """Create a wrapper class for the forward SDE (VP type).
17
- ***
18
- Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
19
- We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.
20
- ***
21
- The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).
22
- We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).
23
- Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:
24
- log_alpha_t = self.marginal_log_mean_coeff(t)
25
- sigma_t = self.marginal_std(t)
26
- lambda_t = self.marginal_lambda(t)
27
- Moreover, as lambda(t) is an invertible function, we also support its inverse function:
28
- t = self.inverse_lambda(lambda_t)
29
- ===============================================================
30
- We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).
31
- 1. For discrete-time DPMs:
32
- For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:
33
- t_i = (i + 1) / N
34
- e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.
35
- We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.
36
- Args:
37
- betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)
38
- alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)
39
- Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.
40
- **Important**: Please pay special attention for the args for `alphas_cumprod`:
41
- The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that
42
- q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).
43
- Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have
44
- alpha_{t_n} = \sqrt{\hat{alpha_n}},
45
- and
46
- log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).
47
- 2. For continuous-time DPMs:
48
- We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise
49
- schedule are the default settings in DDPM and improved-DDPM:
50
- Args:
51
- beta_min: A `float` number. The smallest beta for the linear schedule.
52
- beta_max: A `float` number. The largest beta for the linear schedule.
53
- cosine_s: A `float` number. The hyperparameter in the cosine schedule.
54
- cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.
55
- T: A `float` number. The ending time of the forward process.
56
- ===============================================================
57
- Args:
58
- schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,
59
- 'linear' or 'cosine' for continuous-time DPMs.
60
- Returns:
61
- A wrapper object of the forward SDE (VP type).
62
-
63
- ===============================================================
64
- Example:
65
- # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):
66
- >>> ns = NoiseScheduleVP('discrete', betas=betas)
67
- # For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):
68
- >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
69
- # For continuous-time DPMs (VPSDE), linear schedule:
70
- >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)
71
- """
72
-
73
- if schedule not in ['discrete', 'linear', 'cosine']:
74
- raise ValueError(
75
- "Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(
76
- schedule))
77
-
78
- self.schedule = schedule
79
- if schedule == 'discrete':
80
- if betas is not None:
81
- log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)
82
- else:
83
- assert alphas_cumprod is not None
84
- log_alphas = 0.5 * torch.log(alphas_cumprod)
85
- self.total_N = len(log_alphas)
86
- self.T = 1.
87
- self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))
88
- self.log_alpha_array = log_alphas.reshape((1, -1,))
89
- else:
90
- self.total_N = 1000
91
- self.beta_0 = continuous_beta_0
92
- self.beta_1 = continuous_beta_1
93
- self.cosine_s = 0.008
94
- self.cosine_beta_max = 999.
95
- self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (
96
- 1. + self.cosine_s) / math.pi - self.cosine_s
97
- self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))
98
- self.schedule = schedule
99
- if schedule == 'cosine':
100
- # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.
101
- # Note that T = 0.9946 may be not the optimal setting. However, we find it works well.
102
- self.T = 0.9946
103
- else:
104
- self.T = 1.
105
-
106
- def marginal_log_mean_coeff(self, t):
107
- """
108
- Compute log(alpha_t) of a given continuous-time label t in [0, T].
109
- """
110
- if self.schedule == 'discrete':
111
- return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device),
112
- self.log_alpha_array.to(t.device)).reshape((-1))
113
- elif self.schedule == 'linear':
114
- return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0
115
- elif self.schedule == 'cosine':
116
- log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))
117
- log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0
118
- return log_alpha_t
119
-
120
- def marginal_alpha(self, t):
121
- """
122
- Compute alpha_t of a given continuous-time label t in [0, T].
123
- """
124
- return torch.exp(self.marginal_log_mean_coeff(t))
125
-
126
- def marginal_std(self, t):
127
- """
128
- Compute sigma_t of a given continuous-time label t in [0, T].
129
- """
130
- return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
131
-
132
- def marginal_lambda(self, t):
133
- """
134
- Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
135
- """
136
- log_mean_coeff = self.marginal_log_mean_coeff(t)
137
- log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
138
- return log_mean_coeff - log_std
139
-
140
- def inverse_lambda(self, lamb):
141
- """
142
- Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
143
- """
144
- if self.schedule == 'linear':
145
- tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
146
- Delta = self.beta_0 ** 2 + tmp
147
- return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)
148
- elif self.schedule == 'discrete':
149
- log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)
150
- t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]),
151
- torch.flip(self.t_array.to(lamb.device), [1]))
152
- return t.reshape((-1,))
153
- else:
154
- log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
155
- t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (
156
- 1. + self.cosine_s) / math.pi - self.cosine_s
157
- t = t_fn(log_alpha)
158
- return t
159
-
160
-
161
- def model_wrapper(
162
- model,
163
- noise_schedule,
164
- model_type="noise",
165
- model_kwargs={},
166
- guidance_type="uncond",
167
- condition=None,
168
- unconditional_condition=None,
169
- guidance_scale=1.,
170
- classifier_fn=None,
171
- classifier_kwargs={},
172
- ):
173
- """Create a wrapper function for the noise prediction model.
174
- DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to
175
- firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.
176
- We support four types of the diffusion model by setting `model_type`:
177
- 1. "noise": noise prediction model. (Trained by predicting noise).
178
- 2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).
179
- 3. "v": velocity prediction model. (Trained by predicting the velocity).
180
- The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].
181
- [1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."
182
- arXiv preprint arXiv:2202.00512 (2022).
183
- [2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."
184
- arXiv preprint arXiv:2210.02303 (2022).
185
-
186
- 4. "score": marginal score function. (Trained by denoising score matching).
187
- Note that the score function and the noise prediction model follows a simple relationship:
188
- ```
189
- noise(x_t, t) = -sigma_t * score(x_t, t)
190
- ```
191
- We support three types of guided sampling by DPMs by setting `guidance_type`:
192
- 1. "uncond": unconditional sampling by DPMs.
193
- The input `model` has the following format:
194
- ``
195
- model(x, t_input, **model_kwargs) -> noise | x_start | v | score
196
- ``
197
- 2. "classifier": classifier guidance sampling [3] by DPMs and another classifier.
198
- The input `model` has the following format:
199
- ``
200
- model(x, t_input, **model_kwargs) -> noise | x_start | v | score
201
- ``
202
- The input `classifier_fn` has the following format:
203
- ``
204
- classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)
205
- ``
206
- [3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"
207
- in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.
208
- 3. "classifier-free": classifier-free guidance sampling by conditional DPMs.
209
- The input `model` has the following format:
210
- ``
211
- model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score
212
- ``
213
- And if cond == `unconditional_condition`, the model output is the unconditional DPM output.
214
- [4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."
215
- arXiv preprint arXiv:2207.12598 (2022).
216
-
217
- The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)
218
- or continuous-time labels (i.e. epsilon to T).
219
- We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:
220
- ``
221
- def model_fn(x, t_continuous) -> noise:
222
- t_input = get_model_input_time(t_continuous)
223
- return noise_pred(model, x, t_input, **model_kwargs)
224
- ``
225
- where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.
226
- ===============================================================
227
- Args:
228
- model: A diffusion model with the corresponding format described above.
229
- noise_schedule: A noise schedule object, such as NoiseScheduleVP.
230
- model_type: A `str`. The parameterization type of the diffusion model.
231
- "noise" or "x_start" or "v" or "score".
232
- model_kwargs: A `dict`. A dict for the other inputs of the model function.
233
- guidance_type: A `str`. The type of the guidance for sampling.
234
- "uncond" or "classifier" or "classifier-free".
235
- condition: A pytorch tensor. The condition for the guided sampling.
236
- Only used for "classifier" or "classifier-free" guidance type.
237
- unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.
238
- Only used for "classifier-free" guidance type.
239
- guidance_scale: A `float`. The scale for the guided sampling.
240
- classifier_fn: A classifier function. Only used for the classifier guidance.
241
- classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.
242
- Returns:
243
- A noise prediction model that accepts the noised data and the continuous time as the inputs.
244
- """
245
-
246
- def get_model_input_time(t_continuous):
247
- """
248
- Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.
249
- For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].
250
- For continuous-time DPMs, we just use `t_continuous`.
251
- """
252
- if noise_schedule.schedule == 'discrete':
253
- return (t_continuous - 1. / noise_schedule.total_N) * 1000.
254
- else:
255
- return t_continuous
256
-
257
- def noise_pred_fn(x, t_continuous, cond=None):
258
- if t_continuous.reshape((-1,)).shape[0] == 1:
259
- t_continuous = t_continuous.expand((x.shape[0]))
260
- t_input = get_model_input_time(t_continuous)
261
- if cond is None:
262
- output = model(x, t_input, **model_kwargs)
263
- else:
264
- output = model(x, t_input, cond, **model_kwargs)
265
- if model_type == "noise":
266
- return output
267
- elif model_type == "x_start":
268
- alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
269
- dims = x.dim()
270
- return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)
271
- elif model_type == "v":
272
- alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
273
- dims = x.dim()
274
- return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
275
- elif model_type == "score":
276
- sigma_t = noise_schedule.marginal_std(t_continuous)
277
- dims = x.dim()
278
- return -expand_dims(sigma_t, dims) * output
279
-
280
- def cond_grad_fn(x, t_input):
281
- """
282
- Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
283
- """
284
- with torch.enable_grad():
285
- x_in = x.detach().requires_grad_(True)
286
- log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)
287
- return torch.autograd.grad(log_prob.sum(), x_in)[0]
288
-
289
- def model_fn(x, t_continuous):
290
- """
291
- The noise predicition model function that is used for DPM-Solver.
292
- """
293
- if t_continuous.reshape((-1,)).shape[0] == 1:
294
- t_continuous = t_continuous.expand((x.shape[0]))
295
- if guidance_type == "uncond":
296
- return noise_pred_fn(x, t_continuous)
297
- elif guidance_type == "classifier":
298
- assert classifier_fn is not None
299
- t_input = get_model_input_time(t_continuous)
300
- cond_grad = cond_grad_fn(x, t_input)
301
- sigma_t = noise_schedule.marginal_std(t_continuous)
302
- noise = noise_pred_fn(x, t_continuous)
303
- return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad
304
- elif guidance_type == "classifier-free":
305
- if guidance_scale == 1. or unconditional_condition is None:
306
- return noise_pred_fn(x, t_continuous, cond=condition)
307
- else:
308
- x_in = torch.cat([x] * 2)
309
- t_in = torch.cat([t_continuous] * 2)
310
- c_in = torch.cat([unconditional_condition, condition])
311
- noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
312
- return noise_uncond + guidance_scale * (noise - noise_uncond)
313
-
314
- assert model_type in ["noise", "x_start", "v"]
315
- assert guidance_type in ["uncond", "classifier", "classifier-free"]
316
- return model_fn
317
-
318
-
319
- class DPM_Solver:
320
- def __init__(self, model_fn, noise_schedule, predict_x0=False, thresholding=False, max_val=1.):
321
- """Construct a DPM-Solver.
322
- We support both the noise prediction model ("predicting epsilon") and the data prediction model ("predicting x0").
323
- If `predict_x0` is False, we use the solver for the noise prediction model (DPM-Solver).
324
- If `predict_x0` is True, we use the solver for the data prediction model (DPM-Solver++).
325
- In such case, we further support the "dynamic thresholding" in [1] when `thresholding` is True.
326
- The "dynamic thresholding" can greatly improve the sample quality for pixel-space DPMs with large guidance scales.
327
- Args:
328
- model_fn: A noise prediction model function which accepts the continuous-time input (t in [epsilon, T]):
329
- ``
330
- def model_fn(x, t_continuous):
331
- return noise
332
- ``
333
- noise_schedule: A noise schedule object, such as NoiseScheduleVP.
334
- predict_x0: A `bool`. If true, use the data prediction model; else, use the noise prediction model.
335
- thresholding: A `bool`. Valid when `predict_x0` is True. Whether to use the "dynamic thresholding" in [1].
336
- max_val: A `float`. Valid when both `predict_x0` and `thresholding` are True. The max value for thresholding.
337
-
338
- [1] Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022b.
339
- """
340
- self.model = model_fn
341
- self.noise_schedule = noise_schedule
342
- self.predict_x0 = predict_x0
343
- self.thresholding = thresholding
344
- self.max_val = max_val
345
-
346
- def noise_prediction_fn(self, x, t):
347
- """
348
- Return the noise prediction model.
349
- """
350
- return self.model(x, t)
351
-
352
- def data_prediction_fn(self, x, t):
353
- """
354
- Return the data prediction model (with thresholding).
355
- """
356
- noise = self.noise_prediction_fn(x, t)
357
- dims = x.dim()
358
- alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
359
- x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
360
- if self.thresholding:
361
- p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
362
- s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
363
- s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
364
- x0 = torch.clamp(x0, -s, s) / s
365
- return x0
366
-
367
- def model_fn(self, x, t):
368
- """
369
- Convert the model to the noise prediction model or the data prediction model.
370
- """
371
- if self.predict_x0:
372
- return self.data_prediction_fn(x, t)
373
- else:
374
- return self.noise_prediction_fn(x, t)
375
-
376
- def get_time_steps(self, skip_type, t_T, t_0, N, device):
377
- """Compute the intermediate time steps for sampling.
378
- Args:
379
- skip_type: A `str`. The type for the spacing of the time steps. We support three types:
380
- - 'logSNR': uniform logSNR for the time steps.
381
- - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
382
- - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
383
- t_T: A `float`. The starting time of the sampling (default is T).
384
- t_0: A `float`. The ending time of the sampling (default is epsilon).
385
- N: A `int`. The total number of the spacing of the time steps.
386
- device: A torch device.
387
- Returns:
388
- A pytorch tensor of the time steps, with the shape (N + 1,).
389
- """
390
- if skip_type == 'logSNR':
391
- lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
392
- lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
393
- logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
394
- return self.noise_schedule.inverse_lambda(logSNR_steps)
395
- elif skip_type == 'time_uniform':
396
- return torch.linspace(t_T, t_0, N + 1).to(device)
397
- elif skip_type == 'time_quadratic':
398
- t_order = 2
399
- t = torch.linspace(t_T ** (1. / t_order), t_0 ** (1. / t_order), N + 1).pow(t_order).to(device)
400
- return t
401
- else:
402
- raise ValueError(
403
- "Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
404
-
405
- def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
406
- """
407
- Get the order of each step for sampling by the singlestep DPM-Solver.
408
- We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast".
409
- Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is:
410
- - If order == 1:
411
- We take `steps` of DPM-Solver-1 (i.e. DDIM).
412
- - If order == 2:
413
- - Denote K = (steps // 2). We take K or (K + 1) intermediate time steps for sampling.
414
- - If steps % 2 == 0, we use K steps of DPM-Solver-2.
415
- - If steps % 2 == 1, we use K steps of DPM-Solver-2 and 1 step of DPM-Solver-1.
416
- - If order == 3:
417
- - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
418
- - If steps % 3 == 0, we use (K - 2) steps of DPM-Solver-3, and 1 step of DPM-Solver-2 and 1 step of DPM-Solver-1.
419
- - If steps % 3 == 1, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-1.
420
- - If steps % 3 == 2, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-2.
421
- ============================================
422
- Args:
423
- order: A `int`. The max order for the solver (2 or 3).
424
- steps: A `int`. The total number of function evaluations (NFE).
425
- skip_type: A `str`. The type for the spacing of the time steps. We support three types:
426
- - 'logSNR': uniform logSNR for the time steps.
427
- - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
428
- - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
429
- t_T: A `float`. The starting time of the sampling (default is T).
430
- t_0: A `float`. The ending time of the sampling (default is epsilon).
431
- device: A torch device.
432
- Returns:
433
- orders: A list of the solver order of each step.
434
- """
435
- if order == 3:
436
- K = steps // 3 + 1
437
- if steps % 3 == 0:
438
- orders = [3, ] * (K - 2) + [2, 1]
439
- elif steps % 3 == 1:
440
- orders = [3, ] * (K - 1) + [1]
441
- else:
442
- orders = [3, ] * (K - 1) + [2]
443
- elif order == 2:
444
- if steps % 2 == 0:
445
- K = steps // 2
446
- orders = [2, ] * K
447
- else:
448
- K = steps // 2 + 1
449
- orders = [2, ] * (K - 1) + [1]
450
- elif order == 1:
451
- K = 1
452
- orders = [1, ] * steps
453
- else:
454
- raise ValueError("'order' must be '1' or '2' or '3'.")
455
- if skip_type == 'logSNR':
456
- # To reproduce the results in DPM-Solver paper
457
- timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
458
- else:
459
- timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[
460
- torch.cumsum(torch.tensor([0, ] + orders)).to(device)]
461
- return timesteps_outer, orders
462
-
463
- def denoise_to_zero_fn(self, x, s):
464
- """
465
- Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
466
- """
467
- return self.data_prediction_fn(x, s)
468
-
469
- def dpm_solver_first_update(self, x, s, t, model_s=None, return_intermediate=False):
470
- """
471
- DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`.
472
- Args:
473
- x: A pytorch tensor. The initial value at time `s`.
474
- s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
475
- t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
476
- model_s: A pytorch tensor. The model function evaluated at time `s`.
477
- If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
478
- return_intermediate: A `bool`. If true, also return the model value at time `s`.
479
- Returns:
480
- x_t: A pytorch tensor. The approximated solution at time `t`.
481
- """
482
- ns = self.noise_schedule
483
- dims = x.dim()
484
- lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
485
- h = lambda_t - lambda_s
486
- log_alpha_s, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(t)
487
- sigma_s, sigma_t = ns.marginal_std(s), ns.marginal_std(t)
488
- alpha_t = torch.exp(log_alpha_t)
489
-
490
- if self.predict_x0:
491
- phi_1 = torch.expm1(-h)
492
- if model_s is None:
493
- model_s = self.model_fn(x, s)
494
- x_t = (
495
- expand_dims(sigma_t / sigma_s, dims) * x
496
- - expand_dims(alpha_t * phi_1, dims) * model_s
497
- )
498
- if return_intermediate:
499
- return x_t, {'model_s': model_s}
500
- else:
501
- return x_t
502
- else:
503
- phi_1 = torch.expm1(h)
504
- if model_s is None:
505
- model_s = self.model_fn(x, s)
506
- x_t = (
507
- expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
508
- - expand_dims(sigma_t * phi_1, dims) * model_s
509
- )
510
- if return_intermediate:
511
- return x_t, {'model_s': model_s}
512
- else:
513
- return x_t
514
-
515
- def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False,
516
- solver_type='dpm_solver'):
517
- """
518
- Singlestep solver DPM-Solver-2 from time `s` to time `t`.
519
- Args:
520
- x: A pytorch tensor. The initial value at time `s`.
521
- s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
522
- t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
523
- r1: A `float`. The hyperparameter of the second-order solver.
524
- model_s: A pytorch tensor. The model function evaluated at time `s`.
525
- If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
526
- return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time).
527
- solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
528
- The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
529
- Returns:
530
- x_t: A pytorch tensor. The approximated solution at time `t`.
531
- """
532
- if solver_type not in ['dpm_solver', 'taylor']:
533
- raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
534
- if r1 is None:
535
- r1 = 0.5
536
- ns = self.noise_schedule
537
- dims = x.dim()
538
- lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
539
- h = lambda_t - lambda_s
540
- lambda_s1 = lambda_s + r1 * h
541
- s1 = ns.inverse_lambda(lambda_s1)
542
- log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(
543
- s1), ns.marginal_log_mean_coeff(t)
544
- sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t)
545
- alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t)
546
-
547
- if self.predict_x0:
548
- phi_11 = torch.expm1(-r1 * h)
549
- phi_1 = torch.expm1(-h)
550
-
551
- if model_s is None:
552
- model_s = self.model_fn(x, s)
553
- x_s1 = (
554
- expand_dims(sigma_s1 / sigma_s, dims) * x
555
- - expand_dims(alpha_s1 * phi_11, dims) * model_s
556
- )
557
- model_s1 = self.model_fn(x_s1, s1)
558
- if solver_type == 'dpm_solver':
559
- x_t = (
560
- expand_dims(sigma_t / sigma_s, dims) * x
561
- - expand_dims(alpha_t * phi_1, dims) * model_s
562
- - (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s)
563
- )
564
- elif solver_type == 'taylor':
565
- x_t = (
566
- expand_dims(sigma_t / sigma_s, dims) * x
567
- - expand_dims(alpha_t * phi_1, dims) * model_s
568
- + (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * (
569
- model_s1 - model_s)
570
- )
571
- else:
572
- phi_11 = torch.expm1(r1 * h)
573
- phi_1 = torch.expm1(h)
574
-
575
- if model_s is None:
576
- model_s = self.model_fn(x, s)
577
- x_s1 = (
578
- expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
579
- - expand_dims(sigma_s1 * phi_11, dims) * model_s
580
- )
581
- model_s1 = self.model_fn(x_s1, s1)
582
- if solver_type == 'dpm_solver':
583
- x_t = (
584
- expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
585
- - expand_dims(sigma_t * phi_1, dims) * model_s
586
- - (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s)
587
- )
588
- elif solver_type == 'taylor':
589
- x_t = (
590
- expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
591
- - expand_dims(sigma_t * phi_1, dims) * model_s
592
- - (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s)
593
- )
594
- if return_intermediate:
595
- return x_t, {'model_s': model_s, 'model_s1': model_s1}
596
- else:
597
- return x_t
598
-
599
- def singlestep_dpm_solver_third_update(self, x, s, t, r1=1. / 3., r2=2. / 3., model_s=None, model_s1=None,
600
- return_intermediate=False, solver_type='dpm_solver'):
601
- """
602
- Singlestep solver DPM-Solver-3 from time `s` to time `t`.
603
- Args:
604
- x: A pytorch tensor. The initial value at time `s`.
605
- s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
606
- t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
607
- r1: A `float`. The hyperparameter of the third-order solver.
608
- r2: A `float`. The hyperparameter of the third-order solver.
609
- model_s: A pytorch tensor. The model function evaluated at time `s`.
610
- If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
611
- model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`).
612
- If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it.
613
- return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
614
- solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
615
- The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
616
- Returns:
617
- x_t: A pytorch tensor. The approximated solution at time `t`.
618
- """
619
- if solver_type not in ['dpm_solver', 'taylor']:
620
- raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
621
- if r1 is None:
622
- r1 = 1. / 3.
623
- if r2 is None:
624
- r2 = 2. / 3.
625
- ns = self.noise_schedule
626
- dims = x.dim()
627
- lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
628
- h = lambda_t - lambda_s
629
- lambda_s1 = lambda_s + r1 * h
630
- lambda_s2 = lambda_s + r2 * h
631
- s1 = ns.inverse_lambda(lambda_s1)
632
- s2 = ns.inverse_lambda(lambda_s2)
633
- log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff(
634
- s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t)
635
- sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(
636
- s2), ns.marginal_std(t)
637
- alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t)
638
-
639
- if self.predict_x0:
640
- phi_11 = torch.expm1(-r1 * h)
641
- phi_12 = torch.expm1(-r2 * h)
642
- phi_1 = torch.expm1(-h)
643
- phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1.
644
- phi_2 = phi_1 / h + 1.
645
- phi_3 = phi_2 / h - 0.5
646
-
647
- if model_s is None:
648
- model_s = self.model_fn(x, s)
649
- if model_s1 is None:
650
- x_s1 = (
651
- expand_dims(sigma_s1 / sigma_s, dims) * x
652
- - expand_dims(alpha_s1 * phi_11, dims) * model_s
653
- )
654
- model_s1 = self.model_fn(x_s1, s1)
655
- x_s2 = (
656
- expand_dims(sigma_s2 / sigma_s, dims) * x
657
- - expand_dims(alpha_s2 * phi_12, dims) * model_s
658
- + r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s)
659
- )
660
- model_s2 = self.model_fn(x_s2, s2)
661
- if solver_type == 'dpm_solver':
662
- x_t = (
663
- expand_dims(sigma_t / sigma_s, dims) * x
664
- - expand_dims(alpha_t * phi_1, dims) * model_s
665
- + (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s)
666
- )
667
- elif solver_type == 'taylor':
668
- D1_0 = (1. / r1) * (model_s1 - model_s)
669
- D1_1 = (1. / r2) * (model_s2 - model_s)
670
- D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
671
- D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
672
- x_t = (
673
- expand_dims(sigma_t / sigma_s, dims) * x
674
- - expand_dims(alpha_t * phi_1, dims) * model_s
675
- + expand_dims(alpha_t * phi_2, dims) * D1
676
- - expand_dims(alpha_t * phi_3, dims) * D2
677
- )
678
- else:
679
- phi_11 = torch.expm1(r1 * h)
680
- phi_12 = torch.expm1(r2 * h)
681
- phi_1 = torch.expm1(h)
682
- phi_22 = torch.expm1(r2 * h) / (r2 * h) - 1.
683
- phi_2 = phi_1 / h - 1.
684
- phi_3 = phi_2 / h - 0.5
685
-
686
- if model_s is None:
687
- model_s = self.model_fn(x, s)
688
- if model_s1 is None:
689
- x_s1 = (
690
- expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
691
- - expand_dims(sigma_s1 * phi_11, dims) * model_s
692
- )
693
- model_s1 = self.model_fn(x_s1, s1)
694
- x_s2 = (
695
- expand_dims(torch.exp(log_alpha_s2 - log_alpha_s), dims) * x
696
- - expand_dims(sigma_s2 * phi_12, dims) * model_s
697
- - r2 / r1 * expand_dims(sigma_s2 * phi_22, dims) * (model_s1 - model_s)
698
- )
699
- model_s2 = self.model_fn(x_s2, s2)
700
- if solver_type == 'dpm_solver':
701
- x_t = (
702
- expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
703
- - expand_dims(sigma_t * phi_1, dims) * model_s
704
- - (1. / r2) * expand_dims(sigma_t * phi_2, dims) * (model_s2 - model_s)
705
- )
706
- elif solver_type == 'taylor':
707
- D1_0 = (1. / r1) * (model_s1 - model_s)
708
- D1_1 = (1. / r2) * (model_s2 - model_s)
709
- D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
710
- D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
711
- x_t = (
712
- expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
713
- - expand_dims(sigma_t * phi_1, dims) * model_s
714
- - expand_dims(sigma_t * phi_2, dims) * D1
715
- - expand_dims(sigma_t * phi_3, dims) * D2
716
- )
717
-
718
- if return_intermediate:
719
- return x_t, {'model_s': model_s, 'model_s1': model_s1, 'model_s2': model_s2}
720
- else:
721
- return x_t
722
-
723
- def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpm_solver"):
724
- """
725
- Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`.
726
- Args:
727
- x: A pytorch tensor. The initial value at time `s`.
728
- model_prev_list: A list of pytorch tensor. The previous computed model values.
729
- t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
730
- t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
731
- solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
732
- The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
733
- Returns:
734
- x_t: A pytorch tensor. The approximated solution at time `t`.
735
- """
736
- if solver_type not in ['dpm_solver', 'taylor']:
737
- raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
738
- ns = self.noise_schedule
739
- dims = x.dim()
740
- model_prev_1, model_prev_0 = model_prev_list
741
- t_prev_1, t_prev_0 = t_prev_list
742
- lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_1), ns.marginal_lambda(
743
- t_prev_0), ns.marginal_lambda(t)
744
- log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
745
- sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
746
- alpha_t = torch.exp(log_alpha_t)
747
-
748
- h_0 = lambda_prev_0 - lambda_prev_1
749
- h = lambda_t - lambda_prev_0
750
- r0 = h_0 / h
751
- D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
752
- if self.predict_x0:
753
- if solver_type == 'dpm_solver':
754
- x_t = (
755
- expand_dims(sigma_t / sigma_prev_0, dims) * x
756
- - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
757
- - 0.5 * expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * D1_0
758
- )
759
- elif solver_type == 'taylor':
760
- x_t = (
761
- expand_dims(sigma_t / sigma_prev_0, dims) * x
762
- - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
763
- + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1_0
764
- )
765
- else:
766
- if solver_type == 'dpm_solver':
767
- x_t = (
768
- expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
769
- - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
770
- - 0.5 * expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * D1_0
771
- )
772
- elif solver_type == 'taylor':
773
- x_t = (
774
- expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
775
- - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
776
- - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1_0
777
- )
778
- return x_t
779
-
780
- def multistep_dpm_solver_third_update(self, x, model_prev_list, t_prev_list, t, solver_type='dpm_solver'):
781
- """
782
- Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`.
783
- Args:
784
- x: A pytorch tensor. The initial value at time `s`.
785
- model_prev_list: A list of pytorch tensor. The previous computed model values.
786
- t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
787
- t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
788
- solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
789
- The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
790
- Returns:
791
- x_t: A pytorch tensor. The approximated solution at time `t`.
792
- """
793
- ns = self.noise_schedule
794
- dims = x.dim()
795
- model_prev_2, model_prev_1, model_prev_0 = model_prev_list
796
- t_prev_2, t_prev_1, t_prev_0 = t_prev_list
797
- lambda_prev_2, lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_2), ns.marginal_lambda(
798
- t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t)
799
- log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
800
- sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
801
- alpha_t = torch.exp(log_alpha_t)
802
-
803
- h_1 = lambda_prev_1 - lambda_prev_2
804
- h_0 = lambda_prev_0 - lambda_prev_1
805
- h = lambda_t - lambda_prev_0
806
- r0, r1 = h_0 / h, h_1 / h
807
- D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
808
- D1_1 = expand_dims(1. / r1, dims) * (model_prev_1 - model_prev_2)
809
- D1 = D1_0 + expand_dims(r0 / (r0 + r1), dims) * (D1_0 - D1_1)
810
- D2 = expand_dims(1. / (r0 + r1), dims) * (D1_0 - D1_1)
811
- if self.predict_x0:
812
- x_t = (
813
- expand_dims(sigma_t / sigma_prev_0, dims) * x
814
- - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
815
- + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1
816
- - expand_dims(alpha_t * ((torch.exp(-h) - 1. + h) / h ** 2 - 0.5), dims) * D2
817
- )
818
- else:
819
- x_t = (
820
- expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
821
- - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
822
- - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1
823
- - expand_dims(sigma_t * ((torch.exp(h) - 1. - h) / h ** 2 - 0.5), dims) * D2
824
- )
825
- return x_t
826
-
827
- def singlestep_dpm_solver_update(self, x, s, t, order, return_intermediate=False, solver_type='dpm_solver', r1=None,
828
- r2=None):
829
- """
830
- Singlestep DPM-Solver with the order `order` from time `s` to time `t`.
831
- Args:
832
- x: A pytorch tensor. The initial value at time `s`.
833
- s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
834
- t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
835
- order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
836
- return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
837
- solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
838
- The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
839
- r1: A `float`. The hyperparameter of the second-order or third-order solver.
840
- r2: A `float`. The hyperparameter of the third-order solver.
841
- Returns:
842
- x_t: A pytorch tensor. The approximated solution at time `t`.
843
- """
844
- if order == 1:
845
- return self.dpm_solver_first_update(x, s, t, return_intermediate=return_intermediate)
846
- elif order == 2:
847
- return self.singlestep_dpm_solver_second_update(x, s, t, return_intermediate=return_intermediate,
848
- solver_type=solver_type, r1=r1)
849
- elif order == 3:
850
- return self.singlestep_dpm_solver_third_update(x, s, t, return_intermediate=return_intermediate,
851
- solver_type=solver_type, r1=r1, r2=r2)
852
- else:
853
- raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
854
-
855
- def multistep_dpm_solver_update(self, x, model_prev_list, t_prev_list, t, order, solver_type='dpm_solver'):
856
- """
857
- Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`.
858
- Args:
859
- x: A pytorch tensor. The initial value at time `s`.
860
- model_prev_list: A list of pytorch tensor. The previous computed model values.
861
- t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
862
- t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
863
- order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
864
- solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
865
- The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
866
- Returns:
867
- x_t: A pytorch tensor. The approximated solution at time `t`.
868
- """
869
- if order == 1:
870
- return self.dpm_solver_first_update(x, t_prev_list[-1], t, model_s=model_prev_list[-1])
871
- elif order == 2:
872
- return self.multistep_dpm_solver_second_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
873
- elif order == 3:
874
- return self.multistep_dpm_solver_third_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
875
- else:
876
- raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
877
-
878
- def dpm_solver_adaptive(self, x, order, t_T, t_0, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9, t_err=1e-5,
879
- solver_type='dpm_solver'):
880
- """
881
- The adaptive step size solver based on singlestep DPM-Solver.
882
- Args:
883
- x: A pytorch tensor. The initial value at time `t_T`.
884
- order: A `int`. The (higher) order of the solver. We only support order == 2 or 3.
885
- t_T: A `float`. The starting time of the sampling (default is T).
886
- t_0: A `float`. The ending time of the sampling (default is epsilon).
887
- h_init: A `float`. The initial step size (for logSNR).
888
- atol: A `float`. The absolute tolerance of the solver. For image data, the default setting is 0.0078, followed [1].
889
- rtol: A `float`. The relative tolerance of the solver. The default setting is 0.05.
890
- theta: A `float`. The safety hyperparameter for adapting the step size. The default setting is 0.9, followed [1].
891
- t_err: A `float`. The tolerance for the time. We solve the diffusion ODE until the absolute error between the
892
- current time and `t_0` is less than `t_err`. The default setting is 1e-5.
893
- solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
894
- The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
895
- Returns:
896
- x_0: A pytorch tensor. The approximated solution at time `t_0`.
897
- [1] A. Jolicoeur-Martineau, K. Li, R. PichΓ©-Taillefer, T. Kachman, and I. Mitliagkas, "Gotta go fast when generating data with score-based models," arXiv preprint arXiv:2105.14080, 2021.
898
- """
899
- ns = self.noise_schedule
900
- s = t_T * torch.ones((x.shape[0],)).to(x)
901
- lambda_s = ns.marginal_lambda(s)
902
- lambda_0 = ns.marginal_lambda(t_0 * torch.ones_like(s).to(x))
903
- h = h_init * torch.ones_like(s).to(x)
904
- x_prev = x
905
- nfe = 0
906
- if order == 2:
907
- r1 = 0.5
908
- lower_update = lambda x, s, t: self.dpm_solver_first_update(x, s, t, return_intermediate=True)
909
- higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1,
910
- solver_type=solver_type,
911
- **kwargs)
912
- elif order == 3:
913
- r1, r2 = 1. / 3., 2. / 3.
914
- lower_update = lambda x, s, t: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1,
915
- return_intermediate=True,
916
- solver_type=solver_type)
917
- higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_third_update(x, s, t, r1=r1, r2=r2,
918
- solver_type=solver_type,
919
- **kwargs)
920
- else:
921
- raise ValueError("For adaptive step size solver, order must be 2 or 3, got {}".format(order))
922
- while torch.abs((s - t_0)).mean() > t_err:
923
- t = ns.inverse_lambda(lambda_s + h)
924
- x_lower, lower_noise_kwargs = lower_update(x, s, t)
925
- x_higher = higher_update(x, s, t, **lower_noise_kwargs)
926
- delta = torch.max(torch.ones_like(x).to(x) * atol, rtol * torch.max(torch.abs(x_lower), torch.abs(x_prev)))
927
- norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True))
928
- E = norm_fn((x_higher - x_lower) / delta).max()
929
- if torch.all(E <= 1.):
930
- x = x_higher
931
- s = t
932
- x_prev = x_lower
933
- lambda_s = ns.marginal_lambda(s)
934
- h = torch.min(theta * h * torch.float_power(E, -1. / order).float(), lambda_0 - lambda_s)
935
- nfe += order
936
- print('adaptive solver nfe', nfe)
937
- return x
938
-
939
- def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform',
940
- method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',
941
- atol=0.0078, rtol=0.05,
942
- ):
943
- """
944
- Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at time `t_start`.
945
- =====================================================
946
- We support the following algorithms for both noise prediction model and data prediction model:
947
- - 'singlestep':
948
- Singlestep DPM-Solver (i.e. "DPM-Solver-fast" in the paper), which combines different orders of singlestep DPM-Solver.
949
- We combine all the singlestep solvers with order <= `order` to use up all the function evaluations (steps).
950
- The total number of function evaluations (NFE) == `steps`.
951
- Given a fixed NFE == `steps`, the sampling procedure is:
952
- - If `order` == 1:
953
- - Denote K = steps. We use K steps of DPM-Solver-1 (i.e. DDIM).
954
- - If `order` == 2:
955
- - Denote K = (steps // 2) + (steps % 2). We take K intermediate time steps for sampling.
956
- - If steps % 2 == 0, we use K steps of singlestep DPM-Solver-2.
957
- - If steps % 2 == 1, we use (K - 1) steps of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
958
- - If `order` == 3:
959
- - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
960
- - If steps % 3 == 0, we use (K - 2) steps of singlestep DPM-Solver-3, and 1 step of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
961
- - If steps % 3 == 1, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of DPM-Solver-1.
962
- - If steps % 3 == 2, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of singlestep DPM-Solver-2.
963
- - 'multistep':
964
- Multistep DPM-Solver with the order of `order`. The total number of function evaluations (NFE) == `steps`.
965
- We initialize the first `order` values by lower order multistep solvers.
966
- Given a fixed NFE == `steps`, the sampling procedure is:
967
- Denote K = steps.
968
- - If `order` == 1:
969
- - We use K steps of DPM-Solver-1 (i.e. DDIM).
970
- - If `order` == 2:
971
- - We firstly use 1 step of DPM-Solver-1, then use (K - 1) step of multistep DPM-Solver-2.
972
- - If `order` == 3:
973
- - We firstly use 1 step of DPM-Solver-1, then 1 step of multistep DPM-Solver-2, then (K - 2) step of multistep DPM-Solver-3.
974
- - 'singlestep_fixed':
975
- Fixed order singlestep DPM-Solver (i.e. DPM-Solver-1 or singlestep DPM-Solver-2 or singlestep DPM-Solver-3).
976
- We use singlestep DPM-Solver-`order` for `order`=1 or 2 or 3, with total [`steps` // `order`] * `order` NFE.
977
- - 'adaptive':
978
- Adaptive step size DPM-Solver (i.e. "DPM-Solver-12" and "DPM-Solver-23" in the paper).
979
- We ignore `steps` and use adaptive step size DPM-Solver with a higher order of `order`.
980
- You can adjust the absolute tolerance `atol` and the relative tolerance `rtol` to balance the computatation costs
981
- (NFE) and the sample quality.
982
- - If `order` == 2, we use DPM-Solver-12 which combines DPM-Solver-1 and singlestep DPM-Solver-2.
983
- - If `order` == 3, we use DPM-Solver-23 which combines singlestep DPM-Solver-2 and singlestep DPM-Solver-3.
984
- =====================================================
985
- Some advices for choosing the algorithm:
986
- - For **unconditional sampling** or **guided sampling with small guidance scale** by DPMs:
987
- Use singlestep DPM-Solver ("DPM-Solver-fast" in the paper) with `order = 3`.
988
- e.g.
989
- >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=False)
990
- >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=3,
991
- skip_type='time_uniform', method='singlestep')
992
- - For **guided sampling with large guidance scale** by DPMs:
993
- Use multistep DPM-Solver with `predict_x0 = True` and `order = 2`.
994
- e.g.
995
- >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True)
996
- >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=2,
997
- skip_type='time_uniform', method='multistep')
998
- We support three types of `skip_type`:
999
- - 'logSNR': uniform logSNR for the time steps. **Recommended for low-resolutional images**
1000
- - 'time_uniform': uniform time for the time steps. **Recommended for high-resolutional images**.
1001
- - 'time_quadratic': quadratic time for the time steps.
1002
- =====================================================
1003
- Args:
1004
- x: A pytorch tensor. The initial value at time `t_start`
1005
- e.g. if `t_start` == T, then `x` is a sample from the standard normal distribution.
1006
- steps: A `int`. The total number of function evaluations (NFE).
1007
- t_start: A `float`. The starting time of the sampling.
1008
- If `T` is None, we use self.noise_schedule.T (default is 1.0).
1009
- t_end: A `float`. The ending time of the sampling.
1010
- If `t_end` is None, we use 1. / self.noise_schedule.total_N.
1011
- e.g. if total_N == 1000, we have `t_end` == 1e-3.
1012
- For discrete-time DPMs:
1013
- - We recommend `t_end` == 1. / self.noise_schedule.total_N.
1014
- For continuous-time DPMs:
1015
- - We recommend `t_end` == 1e-3 when `steps` <= 15; and `t_end` == 1e-4 when `steps` > 15.
1016
- order: A `int`. The order of DPM-Solver.
1017
- skip_type: A `str`. The type for the spacing of the time steps. 'time_uniform' or 'logSNR' or 'time_quadratic'.
1018
- method: A `str`. The method for sampling. 'singlestep' or 'multistep' or 'singlestep_fixed' or 'adaptive'.
1019
- denoise_to_zero: A `bool`. Whether to denoise to time 0 at the final step.
1020
- Default is `False`. If `denoise_to_zero` is `True`, the total NFE is (`steps` + 1).
1021
- This trick is firstly proposed by DDPM (https://arxiv.org/abs/2006.11239) and
1022
- score_sde (https://arxiv.org/abs/2011.13456). Such trick can improve the FID
1023
- for diffusion models sampling by diffusion SDEs for low-resolutional images
1024
- (such as CIFAR-10). However, we observed that such trick does not matter for
1025
- high-resolutional images. As it needs an additional NFE, we do not recommend
1026
- it for high-resolutional images.
1027
- lower_order_final: A `bool`. Whether to use lower order solvers at the final steps.
1028
- Only valid for `method=multistep` and `steps < 15`. We empirically find that
1029
- this trick is a key to stabilizing the sampling by DPM-Solver with very few steps
1030
- (especially for steps <= 10). So we recommend to set it to be `True`.
1031
- solver_type: A `str`. The taylor expansion type for the solver. `dpm_solver` or `taylor`. We recommend `dpm_solver`.
1032
- atol: A `float`. The absolute tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
1033
- rtol: A `float`. The relative tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
1034
- Returns:
1035
- x_end: A pytorch tensor. The approximated solution at time `t_end`.
1036
- """
1037
- t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
1038
- t_T = self.noise_schedule.T if t_start is None else t_start
1039
- device = x.device
1040
- if method == 'adaptive':
1041
- with torch.no_grad():
1042
- x = self.dpm_solver_adaptive(x, order=order, t_T=t_T, t_0=t_0, atol=atol, rtol=rtol,
1043
- solver_type=solver_type)
1044
- elif method == 'multistep':
1045
- assert steps >= order
1046
- timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
1047
- assert timesteps.shape[0] - 1 == steps
1048
- with torch.no_grad():
1049
- vec_t = timesteps[0].expand((x.shape[0]))
1050
- model_prev_list = [self.model_fn(x, vec_t)]
1051
- t_prev_list = [vec_t]
1052
- # Init the first `order` values by lower order multistep DPM-Solver.
1053
- for init_order in tqdm(range(1, order), desc="DPM init order"):
1054
- vec_t = timesteps[init_order].expand(x.shape[0])
1055
- x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, init_order,
1056
- solver_type=solver_type)
1057
- model_prev_list.append(self.model_fn(x, vec_t))
1058
- t_prev_list.append(vec_t)
1059
- # Compute the remaining values by `order`-th order multistep DPM-Solver.
1060
- for step in tqdm(range(order, steps + 1), desc="DPM multistep"):
1061
- vec_t = timesteps[step].expand(x.shape[0])
1062
- if lower_order_final and steps < 15:
1063
- step_order = min(order, steps + 1 - step)
1064
- else:
1065
- step_order = order
1066
- x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, step_order,
1067
- solver_type=solver_type)
1068
- for i in range(order - 1):
1069
- t_prev_list[i] = t_prev_list[i + 1]
1070
- model_prev_list[i] = model_prev_list[i + 1]
1071
- t_prev_list[-1] = vec_t
1072
- # We do not need to evaluate the final model value.
1073
- if step < steps:
1074
- model_prev_list[-1] = self.model_fn(x, vec_t)
1075
- elif method in ['singlestep', 'singlestep_fixed']:
1076
- if method == 'singlestep':
1077
- timesteps_outer, orders = self.get_orders_and_timesteps_for_singlestep_solver(steps=steps, order=order,
1078
- skip_type=skip_type,
1079
- t_T=t_T, t_0=t_0,
1080
- device=device)
1081
- elif method == 'singlestep_fixed':
1082
- K = steps // order
1083
- orders = [order, ] * K
1084
- timesteps_outer = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=K, device=device)
1085
- for i, order in enumerate(orders):
1086
- t_T_inner, t_0_inner = timesteps_outer[i], timesteps_outer[i + 1]
1087
- timesteps_inner = self.get_time_steps(skip_type=skip_type, t_T=t_T_inner.item(), t_0=t_0_inner.item(),
1088
- N=order, device=device)
1089
- lambda_inner = self.noise_schedule.marginal_lambda(timesteps_inner)
1090
- vec_s, vec_t = t_T_inner.tile(x.shape[0]), t_0_inner.tile(x.shape[0])
1091
- h = lambda_inner[-1] - lambda_inner[0]
1092
- r1 = None if order <= 1 else (lambda_inner[1] - lambda_inner[0]) / h
1093
- r2 = None if order <= 2 else (lambda_inner[2] - lambda_inner[0]) / h
1094
- x = self.singlestep_dpm_solver_update(x, vec_s, vec_t, order, solver_type=solver_type, r1=r1, r2=r2)
1095
- if denoise_to_zero:
1096
- x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
1097
- return x
1098
-
1099
-
1100
- #############################################################
1101
- # other utility functions
1102
- #############################################################
1103
-
1104
- def interpolate_fn(x, xp, yp):
1105
- """
1106
- A piecewise linear function y = f(x), using xp and yp as keypoints.
1107
- We implement f(x) in a differentiable way (i.e. applicable for autograd).
1108
- The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
1109
- Args:
1110
- x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).
1111
- xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
1112
- yp: PyTorch tensor with shape [C, K].
1113
- Returns:
1114
- The function values f(x), with shape [N, C].
1115
- """
1116
- N, K = x.shape[0], xp.shape[1]
1117
- all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
1118
- sorted_all_x, x_indices = torch.sort(all_x, dim=2)
1119
- x_idx = torch.argmin(x_indices, dim=2)
1120
- cand_start_idx = x_idx - 1
1121
- start_idx = torch.where(
1122
- torch.eq(x_idx, 0),
1123
- torch.tensor(1, device=x.device),
1124
- torch.where(
1125
- torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
1126
- ),
1127
- )
1128
- end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
1129
- start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
1130
- end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
1131
- start_idx2 = torch.where(
1132
- torch.eq(x_idx, 0),
1133
- torch.tensor(0, device=x.device),
1134
- torch.where(
1135
- torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
1136
- ),
1137
- )
1138
- y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
1139
- start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
1140
- end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
1141
- cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
1142
- return cand
1143
-
1144
-
1145
- def expand_dims(v, dims):
1146
- """
1147
- Expand the tensor `v` to the dim `dims`.
1148
- Args:
1149
- `v`: a PyTorch tensor with shape [N].
1150
- `dim`: a `int`.
1151
- Returns:
1152
- a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
1153
- """
1154
- return v[(...,) + (None,) * (dims - 1)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/models/diffusion/dpm_solver/sampler.py DELETED
@@ -1,87 +0,0 @@
1
- """SAMPLING ONLY."""
2
- import torch
3
-
4
- from .dpm_solver import NoiseScheduleVP, model_wrapper, DPM_Solver
5
-
6
-
7
- MODEL_TYPES = {
8
- "eps": "noise",
9
- "v": "v"
10
- }
11
-
12
-
13
- class DPMSolverSampler(object):
14
- def __init__(self, model, **kwargs):
15
- super().__init__()
16
- self.model = model
17
- to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device)
18
- self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod))
19
-
20
- def register_buffer(self, name, attr):
21
- if type(attr) == torch.Tensor:
22
- if attr.device != torch.device("cuda"):
23
- attr = attr.to(torch.device("cuda"))
24
- setattr(self, name, attr)
25
-
26
- @torch.no_grad()
27
- def sample(self,
28
- S,
29
- batch_size,
30
- shape,
31
- conditioning=None,
32
- callback=None,
33
- normals_sequence=None,
34
- img_callback=None,
35
- quantize_x0=False,
36
- eta=0.,
37
- mask=None,
38
- x0=None,
39
- temperature=1.,
40
- noise_dropout=0.,
41
- score_corrector=None,
42
- corrector_kwargs=None,
43
- verbose=True,
44
- x_T=None,
45
- log_every_t=100,
46
- unconditional_guidance_scale=1.,
47
- unconditional_conditioning=None,
48
- # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
49
- **kwargs
50
- ):
51
- if conditioning is not None:
52
- if isinstance(conditioning, dict):
53
- cbs = conditioning[list(conditioning.keys())[0]].shape[0]
54
- if cbs != batch_size:
55
- print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
56
- else:
57
- if conditioning.shape[0] != batch_size:
58
- print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
59
-
60
- # sampling
61
- C, H, W = shape
62
- size = (batch_size, C, H, W)
63
-
64
- print(f'Data shape for DPM-Solver sampling is {size}, sampling steps {S}')
65
-
66
- device = self.model.betas.device
67
- if x_T is None:
68
- img = torch.randn(size, device=device)
69
- else:
70
- img = x_T
71
-
72
- ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod)
73
-
74
- model_fn = model_wrapper(
75
- lambda x, t, c: self.model.apply_model(x, t, c),
76
- ns,
77
- model_type=MODEL_TYPES[self.model.parameterization],
78
- guidance_type="classifier-free",
79
- condition=conditioning,
80
- unconditional_condition=unconditional_conditioning,
81
- guidance_scale=unconditional_guidance_scale,
82
- )
83
-
84
- dpm_solver = DPM_Solver(model_fn, ns, predict_x0=True, thresholding=False)
85
- x = dpm_solver.sample(img, steps=S, skip_type="time_uniform", method="multistep", order=2, lower_order_final=True)
86
-
87
- return x.to(device), None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/models/diffusion/plms.py DELETED
@@ -1,244 +0,0 @@
1
- """SAMPLING ONLY."""
2
-
3
- import torch
4
- import numpy as np
5
- from tqdm import tqdm
6
- from functools import partial
7
-
8
- from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
9
- from ldm.models.diffusion.sampling_util import norm_thresholding
10
-
11
-
12
- class PLMSSampler(object):
13
- def __init__(self, model, schedule="linear", **kwargs):
14
- super().__init__()
15
- self.model = model
16
- self.ddpm_num_timesteps = model.num_timesteps
17
- self.schedule = schedule
18
-
19
- def register_buffer(self, name, attr):
20
- if type(attr) == torch.Tensor:
21
- if attr.device != torch.device("cuda"):
22
- attr = attr.to(torch.device("cuda"))
23
- setattr(self, name, attr)
24
-
25
- def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
26
- if ddim_eta != 0:
27
- raise ValueError('ddim_eta must be 0 for PLMS')
28
- self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
29
- num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
30
- alphas_cumprod = self.model.alphas_cumprod
31
- assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
32
- to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
33
-
34
- self.register_buffer('betas', to_torch(self.model.betas))
35
- self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
36
- self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
37
-
38
- # calculations for diffusion q(x_t | x_{t-1}) and others
39
- self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
40
- self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
41
- self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
42
- self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
43
- self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
44
-
45
- # ddim sampling parameters
46
- ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
47
- ddim_timesteps=self.ddim_timesteps,
48
- eta=ddim_eta,verbose=verbose)
49
- self.register_buffer('ddim_sigmas', ddim_sigmas)
50
- self.register_buffer('ddim_alphas', ddim_alphas)
51
- self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
52
- self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
53
- sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
54
- (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
55
- 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
56
- self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
57
-
58
- @torch.no_grad()
59
- def sample(self,
60
- S,
61
- batch_size,
62
- shape,
63
- conditioning=None,
64
- callback=None,
65
- normals_sequence=None,
66
- img_callback=None,
67
- quantize_x0=False,
68
- eta=0.,
69
- mask=None,
70
- x0=None,
71
- temperature=1.,
72
- noise_dropout=0.,
73
- score_corrector=None,
74
- corrector_kwargs=None,
75
- verbose=True,
76
- x_T=None,
77
- log_every_t=100,
78
- unconditional_guidance_scale=1.,
79
- unconditional_conditioning=None,
80
- # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
81
- dynamic_threshold=None,
82
- **kwargs
83
- ):
84
- if conditioning is not None:
85
- if isinstance(conditioning, dict):
86
- cbs = conditioning[list(conditioning.keys())[0]].shape[0]
87
- if cbs != batch_size:
88
- print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
89
- else:
90
- if conditioning.shape[0] != batch_size:
91
- print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
92
-
93
- self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
94
- # sampling
95
- C, H, W = shape
96
- size = (batch_size, C, H, W)
97
- print(f'Data shape for PLMS sampling is {size}')
98
-
99
- samples, intermediates = self.plms_sampling(conditioning, size,
100
- callback=callback,
101
- img_callback=img_callback,
102
- quantize_denoised=quantize_x0,
103
- mask=mask, x0=x0,
104
- ddim_use_original_steps=False,
105
- noise_dropout=noise_dropout,
106
- temperature=temperature,
107
- score_corrector=score_corrector,
108
- corrector_kwargs=corrector_kwargs,
109
- x_T=x_T,
110
- log_every_t=log_every_t,
111
- unconditional_guidance_scale=unconditional_guidance_scale,
112
- unconditional_conditioning=unconditional_conditioning,
113
- dynamic_threshold=dynamic_threshold,
114
- )
115
- return samples, intermediates
116
-
117
- @torch.no_grad()
118
- def plms_sampling(self, cond, shape,
119
- x_T=None, ddim_use_original_steps=False,
120
- callback=None, timesteps=None, quantize_denoised=False,
121
- mask=None, x0=None, img_callback=None, log_every_t=100,
122
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
123
- unconditional_guidance_scale=1., unconditional_conditioning=None,
124
- dynamic_threshold=None):
125
- device = self.model.betas.device
126
- b = shape[0]
127
- if x_T is None:
128
- img = torch.randn(shape, device=device)
129
- else:
130
- img = x_T
131
-
132
- if timesteps is None:
133
- timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
134
- elif timesteps is not None and not ddim_use_original_steps:
135
- subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
136
- timesteps = self.ddim_timesteps[:subset_end]
137
-
138
- intermediates = {'x_inter': [img], 'pred_x0': [img]}
139
- time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps)
140
- total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
141
- print(f"Running PLMS Sampling with {total_steps} timesteps")
142
-
143
- iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps)
144
- old_eps = []
145
-
146
- for i, step in enumerate(iterator):
147
- index = total_steps - i - 1
148
- ts = torch.full((b,), step, device=device, dtype=torch.long)
149
- ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long)
150
-
151
- if mask is not None:
152
- assert x0 is not None
153
- img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
154
- img = img_orig * mask + (1. - mask) * img
155
-
156
- outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
157
- quantize_denoised=quantize_denoised, temperature=temperature,
158
- noise_dropout=noise_dropout, score_corrector=score_corrector,
159
- corrector_kwargs=corrector_kwargs,
160
- unconditional_guidance_scale=unconditional_guidance_scale,
161
- unconditional_conditioning=unconditional_conditioning,
162
- old_eps=old_eps, t_next=ts_next,
163
- dynamic_threshold=dynamic_threshold)
164
- img, pred_x0, e_t = outs
165
- old_eps.append(e_t)
166
- if len(old_eps) >= 4:
167
- old_eps.pop(0)
168
- if callback: callback(i)
169
- if img_callback: img_callback(pred_x0, i)
170
-
171
- if index % log_every_t == 0 or index == total_steps - 1:
172
- intermediates['x_inter'].append(img)
173
- intermediates['pred_x0'].append(pred_x0)
174
-
175
- return img, intermediates
176
-
177
- @torch.no_grad()
178
- def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
179
- temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
180
- unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None,
181
- dynamic_threshold=None):
182
- b, *_, device = *x.shape, x.device
183
-
184
- def get_model_output(x, t):
185
- if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
186
- e_t = self.model.apply_model(x, t, c)
187
- else:
188
- x_in = torch.cat([x] * 2)
189
- t_in = torch.cat([t] * 2)
190
- c_in = torch.cat([unconditional_conditioning, c])
191
- e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
192
- e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
193
-
194
- if score_corrector is not None:
195
- assert self.model.parameterization == "eps"
196
- e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
197
-
198
- return e_t
199
-
200
- alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
201
- alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
202
- sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
203
- sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
204
-
205
- def get_x_prev_and_pred_x0(e_t, index):
206
- # select parameters corresponding to the currently considered timestep
207
- a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
208
- a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
209
- sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
210
- sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
211
-
212
- # current prediction for x_0
213
- pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
214
- if quantize_denoised:
215
- pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
216
- if dynamic_threshold is not None:
217
- pred_x0 = norm_thresholding(pred_x0, dynamic_threshold)
218
- # direction pointing to x_t
219
- dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
220
- noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
221
- if noise_dropout > 0.:
222
- noise = torch.nn.functional.dropout(noise, p=noise_dropout)
223
- x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
224
- return x_prev, pred_x0
225
-
226
- e_t = get_model_output(x, t)
227
- if len(old_eps) == 0:
228
- # Pseudo Improved Euler (2nd order)
229
- x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index)
230
- e_t_next = get_model_output(x_prev, t_next)
231
- e_t_prime = (e_t + e_t_next) / 2
232
- elif len(old_eps) == 1:
233
- # 2nd order Pseudo Linear Multistep (Adams-Bashforth)
234
- e_t_prime = (3 * e_t - old_eps[-1]) / 2
235
- elif len(old_eps) == 2:
236
- # 3nd order Pseudo Linear Multistep (Adams-Bashforth)
237
- e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12
238
- elif len(old_eps) >= 3:
239
- # 4nd order Pseudo Linear Multistep (Adams-Bashforth)
240
- e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24
241
-
242
- x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index)
243
-
244
- return x_prev, pred_x0, e_t
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/models/diffusion/sampling_util.py DELETED
@@ -1,22 +0,0 @@
1
- import torch
2
- import numpy as np
3
-
4
-
5
- def append_dims(x, target_dims):
6
- """Appends dimensions to the end of a tensor until it has target_dims dimensions.
7
- From https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/utils.py"""
8
- dims_to_append = target_dims - x.ndim
9
- if dims_to_append < 0:
10
- raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less')
11
- return x[(...,) + (None,) * dims_to_append]
12
-
13
-
14
- def norm_thresholding(x0, value):
15
- s = append_dims(x0.pow(2).flatten(1).mean(1).sqrt().clamp(min=value), x0.ndim)
16
- return x0 * (value / s)
17
-
18
-
19
- def spatial_norm_thresholding(x0, value):
20
- # b c h w
21
- s = x0.pow(2).mean(1, keepdim=True).sqrt().clamp(min=value)
22
- return x0 * (value / s)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/models/logger.py DELETED
@@ -1,93 +0,0 @@
1
- import os
2
-
3
- import numpy as np
4
- import torch
5
- import torchvision
6
- from PIL import Image
7
- from pytorch_lightning.callbacks import Callback
8
- from pytorch_lightning.utilities.distributed import rank_zero_only
9
-
10
- # import pdb
11
-
12
- class ImageLogger(Callback):
13
- def __init__(self, batch_frequency=2000, max_images=4, clamp=True, increase_log_steps=True,
14
- rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False,
15
- log_images_kwargs=None,ckpt_dir="./ckpt"):
16
- super().__init__()
17
- self.rescale = rescale
18
- self.batch_freq = batch_frequency
19
- self.max_images = max_images
20
- if not increase_log_steps:
21
- self.log_steps = [self.batch_freq]
22
- self.clamp = clamp
23
- self.disabled = disabled
24
- self.log_on_batch_idx = log_on_batch_idx
25
- self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {}
26
- self.log_first_step = log_first_step
27
- self.ckpt_dir=ckpt_dir
28
- self.global_save_num=-2000
29
- self.global_save_num1=-100
30
-
31
- @rank_zero_only
32
- def log_local(self, save_dir, split, images, global_step, current_epoch, batch_idx):
33
- root = os.path.join(save_dir, "image_log", split)
34
- # print(images)
35
- for k in images:
36
- grid = torchvision.utils.make_grid(images[k], nrow=4)
37
- if self.rescale:
38
- grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
39
- grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1)
40
- grid = grid.numpy()
41
- grid = (grid * 255).astype(np.uint8)
42
- filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format(k, global_step, current_epoch, batch_idx)
43
- path = os.path.join(root, filename)
44
- os.makedirs(os.path.split(path)[0], exist_ok=True)
45
- Image.fromarray(grid).save(path)
46
-
47
- def log_img(self, pl_module, batch, batch_idx, split="train"):
48
- check_idx = batch_idx # if self.log_on_batch_idx else pl_module.global_step
49
- if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0
50
- hasattr(pl_module, "log_images") and
51
- callable(pl_module.log_images) and
52
- self.max_images > 0):
53
- logger = type(pl_module.logger)
54
-
55
- is_train = pl_module.training
56
- if is_train:
57
- pl_module.eval()
58
-
59
- with torch.no_grad():
60
- images = pl_module.log_images(batch, split=split, **self.log_images_kwargs)
61
-
62
- for k in images:
63
- N = min(images[k].shape[0], self.max_images)
64
- images[k] = images[k][:N]
65
- if isinstance(images[k], torch.Tensor):
66
- images[k] = images[k].detach().cpu()
67
- if self.clamp:
68
- images[k] = torch.clamp(images[k], -1., 1.)
69
-
70
- self.log_local(pl_module.logger.save_dir, split, images,
71
- pl_module.global_step, pl_module.current_epoch, batch_idx)
72
-
73
- if is_train:
74
- pl_module.train()
75
-
76
- def check_frequency(self, check_idx):
77
- return check_idx % self.batch_freq == 0
78
-
79
- def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
80
- #if not self.disabled:
81
- #if pl_module.global_step%50 == 0:
82
- # if pl_module.current_epoch-self.global_save_num1 > 0:
83
- # print(batch_idx)
84
- if batch_idx % 500 == 0:
85
- # print("inside")
86
- # pdb.set_trace()
87
- # self.global_save_num1=pl_module.current_epoch
88
- self.log_img(pl_module, batch, batch_idx, split="train_"+"ckpt_inpainting_from5625_2+3750_exemplar_only_vae")
89
- #if pl_module.global_step%1200 == 0 and self.check_frequency(batch_idx):
90
- if batch_idx % 1000 == 0:
91
- # if pl_module.current_epoch-self.global_save_num>10 and self.check_frequency(batch_idx):
92
- # self.global_save_num=pl_module.current_epoch
93
- trainer.save_checkpoint(self.ckpt_dir+"/epoch"+str(pl_module.current_epoch)+"_global-step"+str(pl_module.global_step)+".ckpt")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/modules/__pycache__/attention.cpython-38.pyc DELETED
Binary file (19.1 kB)
 
Control-Color/ldm/modules/__pycache__/attention_dcn_control.cpython-38.pyc DELETED
Binary file (23.3 kB)
 
Control-Color/ldm/modules/__pycache__/ema.cpython-38.pyc DELETED
Binary file (3.19 kB)
 
Control-Color/ldm/modules/attention.py DELETED
@@ -1,653 +0,0 @@
1
- from inspect import isfunction
2
- import math
3
- import torch
4
- import torch.nn.functional as F
5
- from torch import nn, einsum
6
- from einops import rearrange, repeat
7
- from typing import Optional, Any
8
-
9
- from ldm.modules.diffusionmodules.util import checkpoint
10
-
11
-
12
- try:
13
- import xformers
14
- import xformers.ops
15
- XFORMERS_IS_AVAILBLE = True
16
- except:
17
- XFORMERS_IS_AVAILBLE = False
18
-
19
- # CrossAttn precision handling
20
- import os
21
- _ATTN_PRECISION = os.environ.get("ATTN_PRECISION", "fp32")
22
-
23
- def exists(val):
24
- return val is not None
25
-
26
-
27
- def uniq(arr):
28
- return{el: True for el in arr}.keys()
29
-
30
-
31
- def default(val, d):
32
- if exists(val):
33
- return val
34
- return d() if isfunction(d) else d
35
-
36
-
37
- def max_neg_value(t):
38
- return -torch.finfo(t.dtype).max
39
-
40
-
41
- def init_(tensor):
42
- dim = tensor.shape[-1]
43
- std = 1 / math.sqrt(dim)
44
- tensor.uniform_(-std, std)
45
- return tensor
46
-
47
-
48
- # feedforward
49
- class GEGLU(nn.Module):
50
- def __init__(self, dim_in, dim_out):
51
- super().__init__()
52
- self.proj = nn.Linear(dim_in, dim_out * 2)
53
-
54
- def forward(self, x):
55
- x, gate = self.proj(x).chunk(2, dim=-1)
56
- return x * F.gelu(gate)
57
-
58
-
59
- class FeedForward(nn.Module):
60
- def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
61
- super().__init__()
62
- inner_dim = int(dim * mult)
63
- dim_out = default(dim_out, dim)
64
- project_in = nn.Sequential(
65
- nn.Linear(dim, inner_dim),
66
- nn.GELU()
67
- ) if not glu else GEGLU(dim, inner_dim)
68
-
69
- self.net = nn.Sequential(
70
- project_in,
71
- nn.Dropout(dropout),
72
- nn.Linear(inner_dim, dim_out)
73
- )
74
-
75
- def forward(self, x):
76
- return self.net(x)
77
-
78
-
79
- def zero_module(module):
80
- """
81
- Zero out the parameters of a module and return it.
82
- """
83
- for p in module.parameters():
84
- p.detach().zero_()
85
- return module
86
-
87
-
88
- def Normalize(in_channels):
89
- return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
90
-
91
-
92
- class SpatialSelfAttention(nn.Module):
93
- def __init__(self, in_channels):
94
- super().__init__()
95
- self.in_channels = in_channels
96
-
97
- self.norm = Normalize(in_channels)
98
- self.q = torch.nn.Conv2d(in_channels,
99
- in_channels,
100
- kernel_size=1,
101
- stride=1,
102
- padding=0)
103
- self.k = torch.nn.Conv2d(in_channels,
104
- in_channels,
105
- kernel_size=1,
106
- stride=1,
107
- padding=0)
108
- self.v = torch.nn.Conv2d(in_channels,
109
- in_channels,
110
- kernel_size=1,
111
- stride=1,
112
- padding=0)
113
- self.proj_out = torch.nn.Conv2d(in_channels,
114
- in_channels,
115
- kernel_size=1,
116
- stride=1,
117
- padding=0)
118
-
119
- def forward(self, x):
120
- h_ = x
121
- h_ = self.norm(h_)
122
- q = self.q(h_)
123
- k = self.k(h_)
124
- v = self.v(h_)
125
-
126
- # compute attention
127
- b,c,h,w = q.shape
128
- q = rearrange(q, 'b c h w -> b (h w) c')
129
- k = rearrange(k, 'b c h w -> b c (h w)')
130
- w_ = torch.einsum('bij,bjk->bik', q, k)
131
-
132
- w_ = w_ * (int(c)**(-0.5))
133
- w_ = torch.nn.functional.softmax(w_, dim=2)
134
-
135
- # attend to values
136
- v = rearrange(v, 'b c h w -> b c (h w)')
137
- w_ = rearrange(w_, 'b i j -> b j i')
138
- h_ = torch.einsum('bij,bjk->bik', v, w_)
139
- h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
140
- h_ = self.proj_out(h_)
141
-
142
- return x+h_
143
-
144
-
145
- class CrossAttention(nn.Module):
146
- def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
147
- super().__init__()
148
- inner_dim = dim_head * heads
149
- context_dim = default(context_dim, query_dim)
150
-
151
- self.scale = dim_head ** -0.5
152
- self.heads = heads
153
-
154
- self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
155
- self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
156
- self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
157
-
158
- self.to_out = nn.Sequential(
159
- nn.Linear(inner_dim, query_dim),
160
- nn.Dropout(dropout)
161
- )
162
- self.attention_probs=None
163
-
164
- def forward(self, x, context=None, mask=None):
165
- h = self.heads
166
-
167
- q = self.to_q(x)
168
- context = default(context, x)
169
- k = self.to_k(context)
170
- v = self.to_v(context)
171
-
172
- q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
173
-
174
- # force cast to fp32 to avoid overflowing
175
- if _ATTN_PRECISION =="fp32":
176
- with torch.autocast(enabled=False, device_type = 'cuda'):
177
- q, k = q.float(), k.float()
178
- sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
179
- else:
180
- sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
181
-
182
- del q, k
183
-
184
- if exists(mask):
185
- mask = rearrange(mask, 'b ... -> b (...)')
186
- max_neg_value = -torch.finfo(sim.dtype).max
187
- mask = repeat(mask, 'b j -> (b h) () j', h=h)
188
- sim.masked_fill_(~mask, max_neg_value)
189
-
190
- # attention, what we cannot get enough of
191
- sim = sim.softmax(dim=-1)
192
- self.attention_probs = sim
193
- #print("similarity",sim.shape)
194
- out = einsum('b i j, b j d -> b i d', sim, v)
195
- out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
196
- return self.to_out(out)
197
-
198
-
199
- class MemoryEfficientCrossAttention(nn.Module):
200
- # https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
201
- def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
202
- super().__init__()
203
- print(f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, context_dim is {context_dim} and using "
204
- f"{heads} heads.")
205
- inner_dim = dim_head * heads
206
- context_dim = default(context_dim, query_dim)
207
-
208
- self.heads = heads
209
- self.dim_head = dim_head
210
-
211
- self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
212
- self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
213
- self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
214
-
215
- self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
216
- self.attention_op: Optional[Any] = None
217
- self.attention_probs=None
218
-
219
- def forward(self, x, context=None, mask=None):#,timestep=None):
220
- h = self.heads
221
- q = self.to_q(x)
222
- context = default(context, x)
223
- k = self.to_k(context)
224
- v = self.to_v(context)
225
-
226
-
227
- b, _, _ = q.shape
228
- q, k, v = map(
229
- lambda t: t.unsqueeze(3)
230
- .reshape(b, t.shape[1], self.heads, self.dim_head)
231
- .permute(0, 2, 1, 3)
232
- .reshape(b * self.heads, t.shape[1], self.dim_head)
233
- .contiguous(),
234
- (q, k, v),
235
- )
236
-
237
- # actually compute the attention, what we cannot get enough of
238
- out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
239
-
240
- if exists(mask):
241
- raise NotImplementedError
242
- out = (
243
- out.unsqueeze(0)
244
- .reshape(b, self.heads, out.shape[1], self.dim_head)
245
- .permute(0, 2, 1, 3)
246
- .reshape(b, out.shape[1], self.heads * self.dim_head)
247
- )
248
- prob=rearrange(out, 'b n (h d) -> (b h) n d', h=h)
249
- prob = einsum('b i d, b j d -> b i j', prob, v)
250
- self.attention_probs = prob
251
-
252
- # print("emb",emb)
253
- # print(timestep)
254
- # if prob.shape[1] ==6144 and prob.shape[2]==6144 and timestep!=None and timestep<100: #and emb==0:
255
- # torch.save(q,"./q1.pt")
256
- # torch.save(k,"./k1.pt")
257
- # torch.save(prob,"./prob.pt")
258
- # print(prob.shape)
259
- return self.to_out(out)
260
-
261
-
262
- class BasicTransformerBlock(nn.Module):
263
- ATTENTION_MODES = {
264
- "softmax": CrossAttention, # vanilla attention
265
- "softmax-xformers": MemoryEfficientCrossAttention
266
- }
267
- def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
268
- disable_self_attn=False):
269
- super().__init__()
270
- attn_mode = "softmax-xformers" if XFORMERS_IS_AVAILBLE else "softmax"
271
- assert attn_mode in self.ATTENTION_MODES
272
- attn_cls = self.ATTENTION_MODES[attn_mode]
273
- self.disable_self_attn = disable_self_attn
274
- self.attn1 = attn_cls(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
275
- context_dim=context_dim if self.disable_self_attn else None) # is a self-attention if not self.disable_self_attn
276
- self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
277
- self.attn2 = attn_cls(query_dim=dim, context_dim=context_dim,
278
- heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none
279
- self.norm1 = nn.LayerNorm(dim)
280
- self.norm2 = nn.LayerNorm(dim)
281
- self.norm3 = nn.LayerNorm(dim)
282
- self.checkpoint = checkpoint
283
-
284
- def forward(self, x, context=None):#, timestep=None):
285
- return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
286
-
287
- def _forward(self, x, context=None):#, timestep=None):
288
- x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + x
289
- x = self.attn2(self.norm2(x), context=context) + x
290
- x = self.ff(self.norm3(x)) + x
291
- return x
292
-
293
- def _trunc_normal_(tensor, mean, std, a, b):
294
- # Cut & paste from PyTorch official master until it's in a few official releases - RW
295
- # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
296
- def norm_cdf(x):
297
- # Computes standard normal cumulative distribution function
298
- return (1. + math.erf(x / math.sqrt(2.))) / 2.
299
-
300
- if (mean < a - 2 * std) or (mean > b + 2 * std):
301
- warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
302
- "The distribution of values may be incorrect.",
303
- stacklevel=2)
304
-
305
- # Values are generated by using a truncated uniform distribution and
306
- # then using the inverse CDF for the normal distribution.
307
- # Get upper and lower cdf values
308
- l = norm_cdf((a - mean) / std)
309
- u = norm_cdf((b - mean) / std)
310
-
311
- # Uniformly fill tensor with values from [l, u], then translate to
312
- # [2l-1, 2u-1].
313
- tensor.uniform_(2 * l - 1, 2 * u - 1)
314
-
315
- # Use inverse cdf transform for normal distribution to get truncated
316
- # standard normal
317
- tensor.erfinv_()
318
-
319
- # Transform to proper mean, std
320
- tensor.mul_(std * math.sqrt(2.))
321
- tensor.add_(mean)
322
-
323
- # Clamp to ensure it's in the proper range
324
- tensor.clamp_(min=a, max=b)
325
- return tensor
326
-
327
-
328
- def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
329
- # type: (Tensor, float, float, float, float) -> Tensor
330
- r"""Fills the input Tensor with values drawn from a truncated
331
- normal distribution. The values are effectively drawn from the
332
- normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
333
- with values outside :math:`[a, b]` redrawn until they are within
334
- the bounds. The method used for generating the random values works
335
- best when :math:`a \leq \text{mean} \leq b`.
336
-
337
- NOTE: this impl is similar to the PyTorch trunc_normal_, the bounds [a, b] are
338
- applied while sampling the normal with mean/std applied, therefore a, b args
339
- should be adjusted to match the range of mean, std args.
340
-
341
- Args:
342
- tensor: an n-dimensional `torch.Tensor`
343
- mean: the mean of the normal distribution
344
- std: the standard deviation of the normal distribution
345
- a: the minimum cutoff value
346
- b: the maximum cutoff value
347
- Examples:
348
- >>> w = torch.empty(3, 5)
349
- >>> nn.init.trunc_normal_(w)
350
- """
351
- with torch.no_grad():
352
- return _trunc_normal_(tensor, mean, std, a, b)
353
-
354
- class PostionalAttention(nn.Module):
355
- def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
356
- proj_drop=0., attn_head_dim=None, use_rpb=False, window_size=14):
357
- super().__init__()
358
- self.num_heads = num_heads
359
- head_dim = dim // num_heads
360
- if attn_head_dim is not None:
361
- head_dim = attn_head_dim
362
- all_head_dim = head_dim * self.num_heads
363
- self.scale = qk_scale or head_dim ** -0.5
364
-
365
- self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
366
- if qkv_bias:
367
- self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
368
- self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
369
- else:
370
- self.q_bias = None
371
- self.v_bias = None
372
-
373
- # relative positional bias option
374
- self.use_rpb = use_rpb
375
- if use_rpb:
376
- self.window_size = window_size
377
- self.rpb_table = nn.Parameter(torch.zeros((2 * window_size - 1) * (2 * window_size - 1), num_heads))
378
- trunc_normal_(self.rpb_table, std=.02)
379
-
380
- coords_h = torch.arange(window_size)
381
- coords_w = torch.arange(window_size)
382
- coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, h, w
383
- coords_flatten = torch.flatten(coords, 1) # 2, h*w
384
- relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, h*w, h*w
385
- relative_coords = relative_coords.permute(1, 2, 0).contiguous() # h*w, h*w, 2
386
- relative_coords[:, :, 0] += window_size - 1 # shift to start from 0
387
- relative_coords[:, :, 1] += window_size - 1
388
- relative_coords[:, :, 0] *= 2 * window_size - 1
389
- relative_position_index = relative_coords.sum(-1) # h*w, h*w
390
- self.register_buffer("relative_position_index", relative_position_index)
391
-
392
- self.attn_drop = nn.Dropout(attn_drop)
393
- self.proj = nn.Linear(all_head_dim, dim)
394
- self.proj_drop = nn.Dropout(proj_drop)
395
-
396
- def forward(self, x):
397
- B, N, C = x.shape
398
- qkv_bias = None
399
- if self.q_bias is not None:
400
- qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
401
- # qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
402
- qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
403
- qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
404
- q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
405
-
406
- q = q * self.scale
407
- attn = (q @ k.transpose(-2, -1))
408
-
409
- if self.use_rpb:
410
- relative_position_bias = self.rpb_table[self.relative_position_index.view(-1)].view(
411
- self.window_size * self.window_size, self.window_size * self.window_size, -1) # h*w,h*w,nH
412
- relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, h*w, h*w
413
- attn += relative_position_bias
414
-
415
- attn = attn.softmax(dim=-1)
416
- attn = self.attn_drop(attn)
417
-
418
- x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
419
- x = self.proj(x)
420
- x = self.proj_drop(x)
421
- return x
422
-
423
-
424
-
425
- class Mlp(nn.Module):
426
- def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
427
- super().__init__()
428
- out_features = out_features or in_features
429
- hidden_features = hidden_features or in_features
430
- self.fc1 = nn.Linear(in_features, hidden_features)
431
- self.act = act_layer()
432
- self.fc2 = nn.Linear(hidden_features, out_features)
433
- self.drop = nn.Dropout(drop)
434
-
435
- def forward(self, x):
436
- x = self.fc1(x)
437
- x = self.act(x)
438
- # x = self.drop(x)
439
- # commit this for the orignal BERT implement
440
- x = self.fc2(x)
441
- x = self.drop(x)
442
- return x
443
-
444
- class Block(nn.Module):
445
-
446
- def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
447
- drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm,
448
- attn_head_dim=None, use_rpb=False, window_size=14):
449
- super().__init__()
450
- self.norm1 = norm_layer(dim)
451
- self.attn = PostionalAttention(
452
- dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
453
- attn_drop=attn_drop, proj_drop=drop, attn_head_dim=attn_head_dim,
454
- use_rpb=use_rpb, window_size=window_size)
455
- # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
456
- self.drop_path = nn.Identity() #DropPath(drop_path) if drop_path > 0. else nn.Identity()
457
- self.norm2 = norm_layer(dim)
458
- mlp_hidden_dim = int(dim * mlp_ratio)
459
- self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
460
-
461
- if init_values > 0:
462
- self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
463
- self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
464
- else:
465
- self.gamma_1, self.gamma_2 = None, None
466
-
467
- def forward(self, x):
468
- if self.gamma_1 is None:
469
- x = x + self.drop_path(self.attn(self.norm1(x)))
470
- x = x + self.drop_path(self.mlp(self.norm2(x)))
471
- else:
472
- x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x)))
473
- x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
474
- return x
475
-
476
- class PatchEmbed(nn.Module):
477
- """ Image to Patch Embedding
478
- """
479
-
480
- def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, mask_cent=False):
481
- super().__init__()
482
- # to_2tuple = _ntuple(2)
483
- # img_size = to_2tuple(img_size)
484
- # patch_size = to_2tuple(patch_size)
485
- img_size = tuple((img_size, img_size))
486
- patch_size = tuple((patch_size,patch_size))
487
- num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
488
- self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
489
- self.img_size = img_size
490
- self.patch_size = patch_size
491
- self.num_patches = num_patches
492
- self.mask_cent = mask_cent
493
-
494
- self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
495
-
496
- # # From PyTorch internals
497
- # def _ntuple(n):
498
- # def parse(x):
499
- # if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
500
- # return tuple(x)
501
- # return tuple(repeat(x, n))
502
- # return parse
503
-
504
- def forward(self, x, **kwargs):
505
- B, C, H, W = x.shape
506
- # FIXME look at relaxing size constraints
507
- assert H == self.img_size[0] and W == self.img_size[1], \
508
- f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
509
- if self.mask_cent:
510
- x[:, -1] = x[:, -1] - 0.5
511
- x = self.proj(x).flatten(2).transpose(1, 2)
512
- return x
513
-
514
- class CnnHead(nn.Module):
515
- def __init__(self, embed_dim, num_classes, window_size):
516
- super().__init__()
517
- self.embed_dim = embed_dim
518
- self.num_classes = num_classes
519
- self.window_size = window_size
520
-
521
- self.head = nn.Conv2d(embed_dim, num_classes, kernel_size=3, stride=1, padding=1, padding_mode='reflect')
522
-
523
- def forward(self, x):
524
- x = rearrange(x, 'b (p1 p2) c -> b c p1 p2', p1=self.window_size, p2=self.window_size)
525
- x = self.head(x)
526
- x = rearrange(x, 'b c p1 p2 -> b (p1 p2) c')
527
- return x
528
-
529
- # sin-cos position encoding
530
- # https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/master/transformer/Models.py#L31
531
-
532
- import numpy as np
533
- def get_sinusoid_encoding_table(n_position, d_hid):
534
- ''' Sinusoid position encoding table '''
535
- # TODO: make it with torch instead of numpy
536
- def get_position_angle_vec(position):
537
- return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
538
-
539
- sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
540
- sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
541
- sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
542
-
543
- return torch.FloatTensor(sinusoid_table).unsqueeze(0)
544
-
545
- class SpatialTransformer(nn.Module):
546
- """
547
- Transformer block for image-like data.
548
- First, project the input (aka embedding)
549
- and reshape to b, t, d.
550
- Then apply standard transformer action.
551
- Finally, reshape to image
552
- NEW: use_linear for more efficiency instead of the 1x1 convs
553
- """
554
- def __init__(self, in_channels, n_heads, d_head,
555
- depth=1, dropout=0., context_dim=None,
556
- disable_self_attn=False, use_linear=False,
557
- use_checkpoint=True):
558
- super().__init__()
559
- if exists(context_dim) and not isinstance(context_dim, list):
560
- context_dim = [context_dim]
561
- self.in_channels = in_channels
562
- inner_dim = n_heads * d_head
563
- self.norm = Normalize(in_channels)
564
- if not use_linear:
565
- self.proj_in = nn.Conv2d(in_channels,
566
- inner_dim,
567
- kernel_size=1,
568
- stride=1,
569
- padding=0)
570
- else:
571
- self.proj_in = nn.Linear(in_channels, inner_dim)
572
-
573
- self.transformer_blocks = nn.ModuleList(
574
- [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],
575
- disable_self_attn=disable_self_attn, checkpoint=use_checkpoint)
576
- for d in range(depth)]
577
- )
578
- if not use_linear:
579
- self.proj_out = zero_module(nn.Conv2d(inner_dim,
580
- in_channels,
581
- kernel_size=1,
582
- stride=1,
583
- padding=0))
584
- else:
585
- self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))
586
- self.use_linear = use_linear
587
- self.map_size = None
588
- # self.cnnhead = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, padding_mode='reflect')
589
-
590
- # embed_dim=192
591
- # img_size=64
592
- # patch_size=8
593
- # self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size,
594
- # in_chans=4, embed_dim=embed_dim, mask_cent=False)
595
- # num_patches = self.patch_embed.num_patches # 2
596
-
597
- # self.pos_embed = get_sinusoid_encoding_table(num_patches, embed_dim)
598
-
599
- # self.cnnhead = CnnHead(embed_dim, num_classes=32, window_size=img_size // patch_size)
600
-
601
- # self.posatnn_block = Block(dim=embed_dim, num_heads=3, mlp_ratio=4., qkv_bias=True, qk_scale=None,
602
- # drop=0., attn_drop=0., norm_layer=nn.LayerNorm,
603
- # init_values=0., use_rpb=True, window_size=img_size // patch_size)
604
- # # self.window_size=8
605
- # self.norm1=nn.LayerNorm(embed_dim)
606
-
607
- def forward(self, x, context=None):#,timestep=None):
608
- # note: if no context is given, cross-attention defaults to self-attention
609
- if not isinstance(context, list):
610
- context = [context]
611
- b, c, h, w = x.shape
612
- x_in = x
613
- x = self.norm(x)
614
- if not self.use_linear:
615
- x = self.proj_in(x)
616
- x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
617
- if self.use_linear:
618
- x = self.proj_in(x)
619
- for i, block in enumerate(self.transformer_blocks):
620
- x = block(x, context=context[i])#,timestep=timestep)
621
- if self.use_linear:
622
- x = self.proj_out(x)
623
-
624
- # x = rearrange(x, 'b (p1 p2) c -> b c p1 p2', p1=self.window_size, p2=self.window_size)
625
- # x = self.cnnhead(x)
626
- # x = rearrange(x, 'b c p1 p2 -> b (p1 p2) c')
627
-
628
- # x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
629
- x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
630
- # print("before",x.shape)
631
-
632
- # if x.shape[1]==4:
633
- # x = self.patch_embed(x)
634
- # print("after PatchEmbed",x.shape)
635
- # x = x + self.pos_embed.type_as(x).to(x.device).clone().detach()
636
-
637
- # x =self.posatnn_block(x)
638
- # x = self.norm1(x)
639
- # print("after norm",x.shape)
640
-
641
- # x = self.cnnhead(x)
642
-
643
- # print("after",x.shape)
644
- if not self.use_linear:
645
- x = self.proj_out(x)
646
-
647
-
648
- self.map_size = x.shape[-2:]
649
- return x + x_in
650
-
651
- # res = self.cnnhead(x+x_in)
652
- # return res
653
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/modules/attention_dcn_control.py DELETED
@@ -1,854 +0,0 @@
1
- from inspect import isfunction
2
- import math
3
- import torch
4
- import torch.nn.functional as F
5
- from torch import nn, einsum
6
- from einops import rearrange, repeat
7
- from typing import Optional, Any
8
-
9
- from ldm.modules.diffusionmodules.util import checkpoint
10
-
11
- import torchvision
12
- from torch.nn.modules.utils import _pair, _single
13
-
14
- try:
15
- import xformers
16
- import xformers.ops
17
- XFORMERS_IS_AVAILBLE = True
18
- except:
19
- XFORMERS_IS_AVAILBLE = False
20
-
21
- # CrossAttn precision handling
22
- import os
23
- _ATTN_PRECISION = os.environ.get("ATTN_PRECISION", "fp32")
24
-
25
- def exists(val):
26
- return val is not None
27
-
28
-
29
- def uniq(arr):
30
- return{el: True for el in arr}.keys()
31
-
32
-
33
- def default(val, d):
34
- if exists(val):
35
- return val
36
- return d() if isfunction(d) else d
37
-
38
-
39
- def max_neg_value(t):
40
- return -torch.finfo(t.dtype).max
41
-
42
-
43
- def init_(tensor):
44
- dim = tensor.shape[-1]
45
- std = 1 / math.sqrt(dim)
46
- tensor.uniform_(-std, std)
47
- return tensor
48
-
49
-
50
- # feedforward
51
- class GEGLU(nn.Module):
52
- def __init__(self, dim_in, dim_out):
53
- super().__init__()
54
- self.proj = nn.Linear(dim_in, dim_out * 2)
55
-
56
- def forward(self, x):
57
- x, gate = self.proj(x).chunk(2, dim=-1)
58
- return x * F.gelu(gate)
59
-
60
-
61
- class FeedForward(nn.Module):
62
- def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
63
- super().__init__()
64
- inner_dim = int(dim * mult)
65
- dim_out = default(dim_out, dim)
66
- project_in = nn.Sequential(
67
- nn.Linear(dim, inner_dim),
68
- nn.GELU()
69
- ) if not glu else GEGLU(dim, inner_dim)
70
-
71
- self.net = nn.Sequential(
72
- project_in,
73
- nn.Dropout(dropout),
74
- nn.Linear(inner_dim, dim_out)
75
- )
76
-
77
- def forward(self, x):
78
- return self.net(x)
79
-
80
-
81
- def zero_module(module):
82
- """
83
- Zero out the parameters of a module and return it.
84
- """
85
- for p in module.parameters():
86
- p.detach().zero_()
87
- return module
88
-
89
-
90
- def Normalize(in_channels):
91
- return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
92
-
93
-
94
- class SpatialSelfAttention(nn.Module):
95
- def __init__(self, in_channels):
96
- super().__init__()
97
- self.in_channels = in_channels
98
-
99
- self.norm = Normalize(in_channels)
100
- self.q = torch.nn.Conv2d(in_channels,
101
- in_channels,
102
- kernel_size=1,
103
- stride=1,
104
- padding=0)
105
- self.k = torch.nn.Conv2d(in_channels,
106
- in_channels,
107
- kernel_size=1,
108
- stride=1,
109
- padding=0)
110
- self.v = torch.nn.Conv2d(in_channels,
111
- in_channels,
112
- kernel_size=1,
113
- stride=1,
114
- padding=0)
115
- self.proj_out = torch.nn.Conv2d(in_channels,
116
- in_channels,
117
- kernel_size=1,
118
- stride=1,
119
- padding=0)
120
-
121
- def forward(self, x):
122
- h_ = x
123
- h_ = self.norm(h_)
124
- q = self.q(h_)
125
- k = self.k(h_)
126
- v = self.v(h_)
127
-
128
- # compute attention
129
- b,c,h,w = q.shape
130
- q = rearrange(q, 'b c h w -> b (h w) c')
131
- k = rearrange(k, 'b c h w -> b c (h w)')
132
- w_ = torch.einsum('bij,bjk->bik', q, k)
133
-
134
- w_ = w_ * (int(c)**(-0.5))
135
- w_ = torch.nn.functional.softmax(w_, dim=2)
136
-
137
- # attend to values
138
- v = rearrange(v, 'b c h w -> b c (h w)')
139
- w_ = rearrange(w_, 'b i j -> b j i')
140
- h_ = torch.einsum('bij,bjk->bik', v, w_)
141
- h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
142
- h_ = self.proj_out(h_)
143
-
144
- return x+h_
145
-
146
-
147
- class CrossAttention(nn.Module):
148
- def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
149
- super().__init__()
150
- inner_dim = dim_head * heads
151
- context_dim = default(context_dim, query_dim)
152
-
153
- self.scale = dim_head ** -0.5
154
- self.heads = heads
155
-
156
- self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
157
- self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
158
- self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
159
-
160
- self.to_out = nn.Sequential(
161
- nn.Linear(inner_dim, query_dim),
162
- nn.Dropout(dropout)
163
- )
164
-
165
- def forward(self, x, context=None, mask=None):
166
- h = self.heads
167
-
168
- q = self.to_q(x)
169
- context = default(context, x)
170
- k = self.to_k(context)
171
- v = self.to_v(context)
172
-
173
- q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
174
-
175
- # force cast to fp32 to avoid overflowing
176
- if _ATTN_PRECISION =="fp32":
177
- with torch.autocast(enabled=False, device_type = 'cuda'):
178
- q, k = q.float(), k.float()
179
- sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
180
- else:
181
- sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
182
-
183
- del q, k
184
-
185
- if exists(mask):
186
- mask = rearrange(mask, 'b ... -> b (...)')
187
- max_neg_value = -torch.finfo(sim.dtype).max
188
- mask = repeat(mask, 'b j -> (b h) () j', h=h)
189
- sim.masked_fill_(~mask, max_neg_value)
190
-
191
- # attention, what we cannot get enough of
192
- sim = sim.softmax(dim=-1)
193
-
194
- out = einsum('b i j, b j d -> b i d', sim, v)
195
- out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
196
- return self.to_out(out)
197
-
198
-
199
- class MemoryEfficientCrossAttention(nn.Module):
200
- # https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
201
- def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
202
- super().__init__()
203
- print(f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, context_dim is {context_dim} and using "
204
- f"{heads} heads.")
205
- inner_dim = dim_head * heads
206
- context_dim = default(context_dim, query_dim)
207
-
208
- self.heads = heads
209
- self.dim_head = dim_head
210
-
211
- self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
212
- self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
213
- self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
214
-
215
- self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
216
- self.attention_op: Optional[Any] = None
217
-
218
- def forward(self, x, context=None, mask=None):
219
- q = self.to_q(x)
220
- context = default(context, x)
221
- k = self.to_k(context)
222
- v = self.to_v(context)
223
-
224
- b, _, _ = q.shape
225
- q, k, v = map(
226
- lambda t: t.unsqueeze(3)
227
- .reshape(b, t.shape[1], self.heads, self.dim_head)
228
- .permute(0, 2, 1, 3)
229
- .reshape(b * self.heads, t.shape[1], self.dim_head)
230
- .contiguous(),
231
- (q, k, v),
232
- )
233
-
234
- # actually compute the attention, what we cannot get enough of
235
- out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
236
-
237
- if exists(mask):
238
- raise NotImplementedError
239
- out = (
240
- out.unsqueeze(0)
241
- .reshape(b, self.heads, out.shape[1], self.dim_head)
242
- .permute(0, 2, 1, 3)
243
- .reshape(b, out.shape[1], self.heads * self.dim_head)
244
- )
245
- return self.to_out(out)
246
-
247
-
248
- class BasicTransformerBlock(nn.Module):
249
- ATTENTION_MODES = {
250
- "softmax": CrossAttention, # vanilla attention
251
- "softmax-xformers": MemoryEfficientCrossAttention
252
- }
253
- def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
254
- disable_self_attn=False):
255
- super().__init__()
256
- attn_mode = "softmax-xformers" if XFORMERS_IS_AVAILBLE else "softmax"
257
- assert attn_mode in self.ATTENTION_MODES
258
- attn_cls = self.ATTENTION_MODES[attn_mode]
259
- self.disable_self_attn = disable_self_attn
260
- self.attn1 = attn_cls(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
261
- context_dim=context_dim if self.disable_self_attn else None) # is a self-attention if not self.disable_self_attn
262
- self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
263
- self.attn2 = attn_cls(query_dim=dim, context_dim=context_dim,
264
- heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none
265
- self.norm1 = nn.LayerNorm(dim)
266
- self.norm2 = nn.LayerNorm(dim)
267
- self.norm3 = nn.LayerNorm(dim)
268
- self.checkpoint = checkpoint
269
-
270
- def forward(self, x, context=None):
271
- return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
272
-
273
- def _forward(self, x, context=None):
274
- x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + x
275
- x = self.attn2(self.norm2(x), context=context) + x
276
- x = self.ff(self.norm3(x)) + x
277
- return x
278
-
279
- def _trunc_normal_(tensor, mean, std, a, b):
280
- # Cut & paste from PyTorch official master until it's in a few official releases - RW
281
- # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
282
- def norm_cdf(x):
283
- # Computes standard normal cumulative distribution function
284
- return (1. + math.erf(x / math.sqrt(2.))) / 2.
285
-
286
- if (mean < a - 2 * std) or (mean > b + 2 * std):
287
- warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
288
- "The distribution of values may be incorrect.",
289
- stacklevel=2)
290
-
291
- # Values are generated by using a truncated uniform distribution and
292
- # then using the inverse CDF for the normal distribution.
293
- # Get upper and lower cdf values
294
- l = norm_cdf((a - mean) / std)
295
- u = norm_cdf((b - mean) / std)
296
-
297
- # Uniformly fill tensor with values from [l, u], then translate to
298
- # [2l-1, 2u-1].
299
- tensor.uniform_(2 * l - 1, 2 * u - 1)
300
-
301
- # Use inverse cdf transform for normal distribution to get truncated
302
- # standard normal
303
- tensor.erfinv_()
304
-
305
- # Transform to proper mean, std
306
- tensor.mul_(std * math.sqrt(2.))
307
- tensor.add_(mean)
308
-
309
- # Clamp to ensure it's in the proper range
310
- tensor.clamp_(min=a, max=b)
311
- return tensor
312
-
313
-
314
- def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
315
- # type: (Tensor, float, float, float, float) -> Tensor
316
- r"""Fills the input Tensor with values drawn from a truncated
317
- normal distribution. The values are effectively drawn from the
318
- normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
319
- with values outside :math:`[a, b]` redrawn until they are within
320
- the bounds. The method used for generating the random values works
321
- best when :math:`a \leq \text{mean} \leq b`.
322
-
323
- NOTE: this impl is similar to the PyTorch trunc_normal_, the bounds [a, b] are
324
- applied while sampling the normal with mean/std applied, therefore a, b args
325
- should be adjusted to match the range of mean, std args.
326
-
327
- Args:
328
- tensor: an n-dimensional `torch.Tensor`
329
- mean: the mean of the normal distribution
330
- std: the standard deviation of the normal distribution
331
- a: the minimum cutoff value
332
- b: the maximum cutoff value
333
- Examples:
334
- >>> w = torch.empty(3, 5)
335
- >>> nn.init.trunc_normal_(w)
336
- """
337
- with torch.no_grad():
338
- return _trunc_normal_(tensor, mean, std, a, b)
339
-
340
- class PostionalAttention(nn.Module):
341
- def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
342
- proj_drop=0., attn_head_dim=None, use_rpb=False, window_size=14):
343
- super().__init__()
344
- self.num_heads = num_heads
345
- head_dim = dim // num_heads
346
- if attn_head_dim is not None:
347
- head_dim = attn_head_dim
348
- all_head_dim = head_dim * self.num_heads
349
- self.scale = qk_scale or head_dim ** -0.5
350
-
351
- self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
352
- if qkv_bias:
353
- self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
354
- self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
355
- else:
356
- self.q_bias = None
357
- self.v_bias = None
358
-
359
- # relative positional bias option
360
- self.use_rpb = use_rpb
361
- if use_rpb:
362
- self.window_size = window_size
363
- self.rpb_table = nn.Parameter(torch.zeros((2 * window_size - 1) * (2 * window_size - 1), num_heads))
364
- trunc_normal_(self.rpb_table, std=.02)
365
-
366
- coords_h = torch.arange(window_size)
367
- coords_w = torch.arange(window_size)
368
- coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, h, w
369
- coords_flatten = torch.flatten(coords, 1) # 2, h*w
370
- relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, h*w, h*w
371
- relative_coords = relative_coords.permute(1, 2, 0).contiguous() # h*w, h*w, 2
372
- relative_coords[:, :, 0] += window_size - 1 # shift to start from 0
373
- relative_coords[:, :, 1] += window_size - 1
374
- relative_coords[:, :, 0] *= 2 * window_size - 1
375
- relative_position_index = relative_coords.sum(-1) # h*w, h*w
376
- self.register_buffer("relative_position_index", relative_position_index)
377
-
378
- self.attn_drop = nn.Dropout(attn_drop)
379
- self.proj = nn.Linear(all_head_dim, dim)
380
- self.proj_drop = nn.Dropout(proj_drop)
381
-
382
- def forward(self, x):
383
- B, N, C = x.shape
384
- qkv_bias = None
385
- if self.q_bias is not None:
386
- qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
387
- # qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
388
- qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
389
- qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
390
- q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
391
-
392
- q = q * self.scale
393
- attn = (q @ k.transpose(-2, -1))
394
-
395
- if self.use_rpb:
396
- relative_position_bias = self.rpb_table[self.relative_position_index.view(-1)].view(
397
- self.window_size * self.window_size, self.window_size * self.window_size, -1) # h*w,h*w,nH
398
- relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, h*w, h*w
399
- attn += relative_position_bias
400
-
401
- attn = attn.softmax(dim=-1)
402
- attn = self.attn_drop(attn)
403
-
404
- x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
405
- x = self.proj(x)
406
- x = self.proj_drop(x)
407
- return x
408
-
409
-
410
-
411
- class Mlp(nn.Module):
412
- def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
413
- super().__init__()
414
- out_features = out_features or in_features
415
- hidden_features = hidden_features or in_features
416
- self.fc1 = nn.Linear(in_features, hidden_features)
417
- self.act = act_layer()
418
- self.fc2 = nn.Linear(hidden_features, out_features)
419
- self.drop = nn.Dropout(drop)
420
-
421
- def forward(self, x):
422
- x = self.fc1(x)
423
- x = self.act(x)
424
- # x = self.drop(x)
425
- # commit this for the orignal BERT implement
426
- x = self.fc2(x)
427
- x = self.drop(x)
428
- return x
429
-
430
- class Block(nn.Module):
431
-
432
- def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
433
- drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm,
434
- attn_head_dim=None, use_rpb=False, window_size=14):
435
- super().__init__()
436
- self.norm1 = norm_layer(dim)
437
- self.attn = PostionalAttention(
438
- dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
439
- attn_drop=attn_drop, proj_drop=drop, attn_head_dim=attn_head_dim,
440
- use_rpb=use_rpb, window_size=window_size)
441
- # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
442
- self.drop_path = nn.Identity() #DropPath(drop_path) if drop_path > 0. else nn.Identity()
443
- self.norm2 = norm_layer(dim)
444
- mlp_hidden_dim = int(dim * mlp_ratio)
445
- self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
446
-
447
- if init_values > 0:
448
- self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
449
- self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
450
- else:
451
- self.gamma_1, self.gamma_2 = None, None
452
-
453
- def forward(self, x):
454
- if self.gamma_1 is None:
455
- x = x + self.drop_path(self.attn(self.norm1(x)))
456
- x = x + self.drop_path(self.mlp(self.norm2(x)))
457
- else:
458
- x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x)))
459
- x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
460
- return x
461
-
462
- class PatchEmbed(nn.Module):
463
- """ Image to Patch Embedding
464
- """
465
-
466
- def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, mask_cent=False):
467
- super().__init__()
468
- # to_2tuple = _ntuple(2)
469
- # img_size = to_2tuple(img_size)
470
- # patch_size = to_2tuple(patch_size)
471
- img_size = tuple((img_size, img_size))
472
- patch_size = tuple((patch_size,patch_size))
473
- num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
474
- self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
475
- self.img_size = img_size
476
- self.patch_size = patch_size
477
- self.num_patches = num_patches
478
- self.mask_cent = mask_cent
479
-
480
- self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
481
-
482
- # # From PyTorch internals
483
- # def _ntuple(n):
484
- # def parse(x):
485
- # if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
486
- # return tuple(x)
487
- # return tuple(repeat(x, n))
488
- # return parse
489
-
490
- def forward(self, x, **kwargs):
491
- B, C, H, W = x.shape
492
- # FIXME look at relaxing size constraints
493
- assert H == self.img_size[0] and W == self.img_size[1], \
494
- f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
495
- if self.mask_cent:
496
- x[:, -1] = x[:, -1] - 0.5
497
- x = self.proj(x).flatten(2).transpose(1, 2)
498
- return x
499
-
500
- class CnnHead(nn.Module):
501
- def __init__(self, embed_dim, num_classes, window_size):
502
- super().__init__()
503
- self.embed_dim = embed_dim
504
- self.num_classes = num_classes
505
- self.window_size = window_size
506
-
507
- self.head = nn.Conv2d(embed_dim, num_classes, kernel_size=3, stride=1, padding=1, padding_mode='reflect')
508
-
509
- def forward(self, x):
510
- x = rearrange(x, 'b (p1 p2) c -> b c p1 p2', p1=self.window_size, p2=self.window_size)
511
- x = self.head(x)
512
- x = rearrange(x, 'b c p1 p2 -> b (p1 p2) c')
513
- return x
514
-
515
- # sin-cos position encoding
516
- # https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/master/transformer/Models.py#L31
517
-
518
- import numpy as np
519
- def get_sinusoid_encoding_table(n_position, d_hid):
520
- ''' Sinusoid position encoding table '''
521
- # TODO: make it with torch instead of numpy
522
- def get_position_angle_vec(position):
523
- return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
524
-
525
- sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
526
- sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
527
- sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
528
-
529
- return torch.FloatTensor(sinusoid_table).unsqueeze(0)
530
-
531
- class ModulatedDeformConv(nn.Module):
532
-
533
- def __init__(self,
534
- in_channels,
535
- out_channels,
536
- kernel_size,
537
- stride=1,
538
- padding=0,
539
- dilation=1,
540
- groups=1,
541
- deformable_groups=1,
542
- bias=True):
543
- super(ModulatedDeformConv, self).__init__()
544
- self.in_channels = in_channels
545
- self.out_channels = out_channels
546
- self.kernel_size = _pair(kernel_size)
547
- self.stride = stride
548
- self.padding = padding
549
- self.dilation = dilation
550
- self.groups = groups
551
- self.deformable_groups = deformable_groups
552
- self.with_bias = bias
553
- # enable compatibility with nn.Conv2d
554
- self.transposed = False
555
- self.output_padding = _single(0)
556
-
557
- self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, *self.kernel_size))
558
- if bias:
559
- self.bias = nn.Parameter(torch.Tensor(out_channels))
560
- else:
561
- self.register_parameter('bias', None)
562
- self.init_weights()
563
-
564
- def init_weights(self):
565
- n = self.in_channels
566
- for k in self.kernel_size:
567
- n *= k
568
- stdv = 1. / math.sqrt(n)
569
- self.weight.data.uniform_(-stdv, stdv)
570
- if self.bias is not None:
571
- self.bias.data.zero_()
572
-
573
- class ModulatedDeformConvPack(ModulatedDeformConv):
574
- """
575
- https://github.com/xinntao/EDVR/blob/master/basicsr/models/ops/dcn/deform_conv.py
576
- A ModulatedDeformable Conv Encapsulation that acts as normal Conv layers.
577
-
578
- Args:
579
- in_channels (int): Same as nn.Conv2d.
580
- out_channels (int): Same as nn.Conv2d.
581
- kernel_size (int or tuple[int]): Same as nn.Conv2d.
582
- stride (int or tuple[int]): Same as nn.Conv2d.
583
- padding (int or tuple[int]): Same as nn.Conv2d.
584
- dilation (int or tuple[int]): Same as nn.Conv2d.
585
- groups (int): Same as nn.Conv2d.
586
- bias (bool or str): If specified as `auto`, it will be decided by the
587
- norm_cfg. Bias will be set as True if norm_cfg is None, otherwise
588
- False.
589
- """
590
-
591
- _version = 2
592
-
593
- def __init__(self, *args, **kwargs):
594
- super(ModulatedDeformConvPack, self).__init__(*args, **kwargs)
595
-
596
- self.conv_offset = nn.Conv2d(
597
- self.in_channels,#self.in_channels+4,
598
- self.deformable_groups * 3 * self.kernel_size[0] * self.kernel_size[1],
599
- kernel_size=self.kernel_size,
600
- stride=_pair(self.stride),
601
- padding=_pair(self.padding),
602
- dilation=_pair(self.dilation),
603
- bias=True)
604
- self.init_weights()
605
-
606
- def init_weights(self):
607
- super(ModulatedDeformConvPack, self).init_weights()
608
- if hasattr(self, 'conv_offset'):
609
- self.conv_offset.weight.data.zero_()
610
- self.conv_offset.bias.data.zero_()
611
-
612
- def forward(self, x):
613
- # out = self.conv_offset(torch.cat((x,gray_content),dim=1))
614
- out = self.conv_offset(x)
615
- o1, o2, mask = torch.chunk(out, 3, dim=1)
616
- offset = torch.cat((o1, o2), dim=1)
617
- mask = torch.sigmoid(mask)
618
-
619
- # return modulated_deform_conv(x, offset, mask, self.weight, self.bias, self.stride, self.padding, self.dilation,
620
- # self.groups, self.deformable_groups)
621
- return torchvision.ops.deform_conv2d(x, offset, self.weight, self.bias, self.stride, self.padding,
622
- self.dilation, mask)
623
-
624
- class SpatialTransformer(nn.Module):
625
- """
626
- Transformer block for image-like data.
627
- First, project the input (aka embedding)
628
- and reshape to b, t, d.
629
- Then apply standard transformer action.
630
- Finally, reshape to image
631
- NEW: use_linear for more efficiency instead of the 1x1 convs
632
- """
633
- def __init__(self, in_channels, n_heads, d_head,
634
- depth=1, dropout=0., context_dim=None,
635
- disable_self_attn=False, use_linear=False,
636
- use_checkpoint=True):
637
- super().__init__()
638
- if exists(context_dim) and not isinstance(context_dim, list):
639
- context_dim = [context_dim]
640
- self.in_channels = in_channels
641
- inner_dim = n_heads * d_head
642
- self.norm = Normalize(in_channels)
643
- if not use_linear:
644
- self.proj_in = nn.Conv2d(in_channels,
645
- inner_dim,
646
- kernel_size=1,
647
- stride=1,
648
- padding=0)
649
- else:
650
- self.proj_in = nn.Linear(in_channels, inner_dim)
651
-
652
- self.transformer_blocks = nn.ModuleList(
653
- [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],
654
- disable_self_attn=disable_self_attn, checkpoint=use_checkpoint)
655
- for d in range(depth)]
656
- )
657
- if not use_linear:
658
- self.proj_out = zero_module(nn.Conv2d(inner_dim,
659
- in_channels,
660
- kernel_size=1,
661
- stride=1,
662
- padding=0))
663
- else:
664
- self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))
665
- self.use_linear = use_linear
666
- # self.dcn_cnn = ModulatedDeformConvPack(inner_dim,
667
- # inner_dim,
668
- # kernel_size=3,
669
- # stride=1,
670
- # padding=1)
671
-
672
- # self.cnnhead = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, padding_mode='reflect')
673
-
674
- # embed_dim=192
675
- # img_size=64
676
- # patch_size=8
677
- # self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size,
678
- # in_chans=4, embed_dim=embed_dim, mask_cent=False)
679
- # num_patches = self.patch_embed.num_patches # 2
680
-
681
- # self.pos_embed = get_sinusoid_encoding_table(num_patches, embed_dim)
682
-
683
- # self.cnnhead = CnnHead(embed_dim, num_classes=32, window_size=img_size // patch_size)
684
-
685
- # self.posatnn_block = Block(dim=embed_dim, num_heads=3, mlp_ratio=4., qkv_bias=True, qk_scale=None,
686
- # drop=0., attn_drop=0., norm_layer=nn.LayerNorm,
687
- # init_values=0., use_rpb=True, window_size=img_size // patch_size)
688
- # # self.window_size=8
689
- # self.norm1=nn.LayerNorm(embed_dim)
690
-
691
- def forward(self, x, context=None,dcn_guide=None):
692
- # note: if no context is given, cross-attention defaults to self-attention
693
- if not isinstance(context, list):
694
- context = [context]
695
- b, c, h, w = x.shape
696
- x_in = x
697
- x = self.norm(x)
698
- if not self.use_linear:
699
- x = self.proj_in(x)
700
- x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
701
- if self.use_linear:
702
- x = self.proj_in(x)
703
- for i, block in enumerate(self.transformer_blocks):
704
- x = block(x, context=context[i])
705
- if self.use_linear:
706
- x = self.proj_out(x)
707
-
708
- # x = rearrange(x, 'b (p1 p2) c -> b c p1 p2', p1=self.window_size, p2=self.window_size)
709
- # x = self.cnnhead(x)
710
- # x = rearrange(x, 'b c p1 p2 -> b (p1 p2) c')
711
-
712
- # x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
713
- x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
714
- # print("before",x.shape)
715
-
716
- # if x.shape[1]==4:
717
- # x = self.patch_embed(x)
718
- # print("after PatchEmbed",x.shape)
719
- # x = x + self.pos_embed.type_as(x).to(x.device).clone().detach()
720
-
721
- # x =self.posatnn_block(x)
722
- # x = self.norm1(x)
723
- # print("after norm",x.shape)
724
-
725
- # x = self.cnnhead(x)
726
-
727
- # x = self.dcn_cnn(x,dcn_guide) ##
728
-
729
- # print("after",x.shape)
730
- if not self.use_linear:
731
- x = self.proj_out(x)
732
-
733
-
734
-
735
- return x + x_in
736
-
737
- # res = self.cnnhead(x+x_in)
738
- # return res
739
-
740
-
741
- class SpatialTransformer_dcn(nn.Module):
742
- """
743
- Transformer block for image-like data.
744
- First, project the input (aka embedding)
745
- and reshape to b, t, d.
746
- Then apply standard transformer action.
747
- Finally, reshape to image
748
- NEW: use_linear for more efficiency instead of the 1x1 convs
749
- """
750
- def __init__(self, in_channels, n_heads, d_head,
751
- depth=1, dropout=0., context_dim=None,
752
- disable_self_attn=False, use_linear=False,
753
- use_checkpoint=True):
754
- super().__init__()
755
- if exists(context_dim) and not isinstance(context_dim, list):
756
- context_dim = [context_dim]
757
- self.in_channels = in_channels
758
- inner_dim = n_heads * d_head
759
- self.norm = Normalize(in_channels)
760
- if not use_linear:
761
- self.proj_in = nn.Conv2d(in_channels,
762
- inner_dim,
763
- kernel_size=1,
764
- stride=1,
765
- padding=0)
766
- else:
767
- self.proj_in = nn.Linear(in_channels, inner_dim)
768
-
769
- self.transformer_blocks = nn.ModuleList(
770
- [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],
771
- disable_self_attn=disable_self_attn, checkpoint=use_checkpoint)
772
- for d in range(depth)]
773
- )
774
- if not use_linear:
775
- self.proj_out = zero_module(nn.Conv2d(inner_dim,
776
- in_channels,
777
- kernel_size=1,
778
- stride=1,
779
- padding=0))
780
- else:
781
- self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))
782
- self.use_linear = use_linear
783
- # print(in_channels,inner_dim)
784
- self.dcn_cnn = ModulatedDeformConvPack(inner_dim,
785
- inner_dim,
786
- kernel_size=3,
787
- stride=1,
788
- padding=1)
789
-
790
- # self.cnnhead = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, padding_mode='reflect')
791
-
792
- # embed_dim=192
793
- # img_size=64
794
- # patch_size=8
795
- # self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size,
796
- # in_chans=4, embed_dim=embed_dim, mask_cent=False)
797
- # num_patches = self.patch_embed.num_patches # 2
798
-
799
- # self.pos_embed = get_sinusoid_encoding_table(num_patches, embed_dim)
800
-
801
- # self.cnnhead = CnnHead(embed_dim, num_classes=32, window_size=img_size // patch_size)
802
-
803
- # self.posatnn_block = Block(dim=embed_dim, num_heads=3, mlp_ratio=4., qkv_bias=True, qk_scale=None,
804
- # drop=0., attn_drop=0., norm_layer=nn.LayerNorm,
805
- # init_values=0., use_rpb=True, window_size=img_size // patch_size)
806
- # # self.window_size=8
807
- # self.norm1=nn.LayerNorm(embed_dim)
808
-
809
- def forward(self, x, context=None,dcn_guide=None):
810
- # note: if no context is given, cross-attention defaults to self-attention
811
- if not isinstance(context, list):
812
- context = [context]
813
- b, c, h, w = x.shape
814
- x_in = x
815
- x = self.norm(x)
816
- if not self.use_linear:
817
- x = self.proj_in(x)
818
- x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
819
- if self.use_linear:
820
- x = self.proj_in(x)
821
- for i, block in enumerate(self.transformer_blocks):
822
- x = block(x, context=context[i])
823
- if self.use_linear:
824
- x = self.proj_out(x)
825
-
826
- # x = rearrange(x, 'b (p1 p2) c -> b c p1 p2', p1=self.window_size, p2=self.window_size)
827
- # x = self.cnnhead(x)
828
- # x = rearrange(x, 'b c p1 p2 -> b (p1 p2) c')
829
-
830
- # x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
831
- x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
832
- # print("before",x.shape)
833
-
834
- # if x.shape[1]==4:
835
- # x = self.patch_embed(x)
836
- # print("after PatchEmbed",x.shape)
837
- # x = x + self.pos_embed.type_as(x).to(x.device).clone().detach()
838
-
839
- # x =self.posatnn_block(x)
840
- # x = self.norm1(x)
841
- # print("after norm",x.shape)
842
-
843
- # x = self.cnnhead(x)
844
- x = self.dcn_cnn(x)
845
- # print("after",x.shape)
846
- if not self.use_linear:
847
- x = self.proj_out(x)
848
-
849
-
850
-
851
- return x + x_in
852
-
853
- # res = self.cnnhead(x+x_in)
854
- # return res
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/modules/diffusionmodules/__init__.py DELETED
File without changes
Control-Color/ldm/modules/diffusionmodules/__pycache__/__init__.cpython-38.pyc DELETED
Binary file (170 Bytes)
 
Control-Color/ldm/modules/diffusionmodules/__pycache__/model.cpython-38.pyc DELETED
Binary file (25.5 kB)
 
Control-Color/ldm/modules/diffusionmodules/__pycache__/model_brefore_dcn.cpython-38.pyc DELETED
Binary file (21.3 kB)
 
Control-Color/ldm/modules/diffusionmodules/__pycache__/openaimodel.cpython-38.pyc DELETED
Binary file (21.6 kB)
 
Control-Color/ldm/modules/diffusionmodules/__pycache__/util.cpython-38.pyc DELETED
Binary file (9.67 kB)
 
Control-Color/ldm/modules/diffusionmodules/model.py DELETED
@@ -1,1107 +0,0 @@
1
- # pytorch_diffusion + derived encoder decoder
2
- import math
3
- import torch
4
- import torch.nn as nn
5
- import torchvision
6
- from torch.nn.modules.utils import _pair, _single
7
- import numpy as np
8
- from einops import rearrange
9
- from typing import Optional, Any
10
-
11
- from ldm.modules.attention import MemoryEfficientCrossAttention
12
-
13
- try:
14
- import xformers
15
- import xformers.ops
16
- XFORMERS_IS_AVAILBLE = True
17
- except:
18
- XFORMERS_IS_AVAILBLE = False
19
- print("No module 'xformers'. Proceeding without it.")
20
-
21
-
22
- def get_timestep_embedding(timesteps, embedding_dim):
23
- """
24
- This matches the implementation in Denoising Diffusion Probabilistic Models:
25
- From Fairseq.
26
- Build sinusoidal embeddings.
27
- This matches the implementation in tensor2tensor, but differs slightly
28
- from the description in Section 3.5 of "Attention Is All You Need".
29
- """
30
- assert len(timesteps.shape) == 1
31
-
32
- half_dim = embedding_dim // 2
33
- emb = math.log(10000) / (half_dim - 1)
34
- emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
35
- emb = emb.to(device=timesteps.device)
36
- emb = timesteps.float()[:, None] * emb[None, :]
37
- emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
38
- if embedding_dim % 2 == 1: # zero pad
39
- emb = torch.nn.functional.pad(emb, (0,1,0,0))
40
- return emb
41
-
42
-
43
- def nonlinearity(x):
44
- # swish
45
- return x*torch.sigmoid(x)
46
-
47
-
48
- def Normalize(in_channels, num_groups=32):
49
- return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
50
-
51
-
52
- class Upsample(nn.Module):
53
- def __init__(self, in_channels, with_conv):
54
- super().__init__()
55
- self.with_conv = with_conv
56
- if self.with_conv:
57
- self.conv = torch.nn.Conv2d(in_channels,
58
- in_channels,
59
- kernel_size=3,
60
- stride=1,
61
- padding=1)
62
-
63
- def forward(self, x):
64
- x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
65
- if self.with_conv:
66
- x = self.conv(x)
67
- return x
68
-
69
-
70
- class Downsample(nn.Module):
71
- def __init__(self, in_channels, with_conv):
72
- super().__init__()
73
- self.with_conv = with_conv
74
- if self.with_conv:
75
- # no asymmetric padding in torch conv, must do it ourselves
76
- self.conv = torch.nn.Conv2d(in_channels,
77
- in_channels,
78
- kernel_size=3,
79
- stride=2,
80
- padding=0)
81
-
82
- def forward(self, x):
83
- if self.with_conv:
84
- pad = (0,1,0,1)
85
- x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
86
- x = self.conv(x)
87
- else:
88
- x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
89
- return x
90
-
91
-
92
- class ResnetBlock(nn.Module):
93
- def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
94
- dropout, temb_channels=512):
95
- super().__init__()
96
- self.in_channels = in_channels
97
- out_channels = in_channels if out_channels is None else out_channels
98
- self.out_channels = out_channels
99
- self.use_conv_shortcut = conv_shortcut
100
-
101
- self.norm1 = Normalize(in_channels)
102
- self.conv1 = torch.nn.Conv2d(in_channels,
103
- out_channels,
104
- kernel_size=3,
105
- stride=1,
106
- padding=1)
107
- if temb_channels > 0:
108
- self.temb_proj = torch.nn.Linear(temb_channels,
109
- out_channels)
110
- self.norm2 = Normalize(out_channels)
111
- self.dropout = torch.nn.Dropout(dropout)
112
- self.conv2 = torch.nn.Conv2d(out_channels,
113
- out_channels,
114
- kernel_size=3,
115
- stride=1,
116
- padding=1)
117
-
118
- if self.in_channels != self.out_channels:
119
- if self.use_conv_shortcut:
120
- self.conv_shortcut = torch.nn.Conv2d(in_channels,
121
- out_channels,
122
- kernel_size=3,
123
- stride=1,
124
- padding=1)
125
- else:
126
- self.nin_shortcut = torch.nn.Conv2d(in_channels,
127
- out_channels,
128
- kernel_size=1,
129
- stride=1,
130
- padding=0)
131
-
132
- def forward(self, x, temb):
133
- h = x
134
- h = self.norm1(h)
135
- h = nonlinearity(h)
136
- h = self.conv1(h)
137
-
138
- if temb is not None:
139
- h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
140
-
141
- h = self.norm2(h)
142
- h = nonlinearity(h)
143
- h = self.dropout(h)
144
- h = self.conv2(h)
145
-
146
- if self.in_channels != self.out_channels:
147
- if self.use_conv_shortcut:
148
- x = self.conv_shortcut(x)
149
- else:
150
- x = self.nin_shortcut(x)
151
-
152
- return x+h
153
-
154
- class ResnetBlock_dcn(nn.Module):
155
- def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
156
- dropout, temb_channels=512):
157
- super().__init__()
158
- self.in_channels = in_channels
159
- out_channels = in_channels if out_channels is None else out_channels
160
- self.out_channels = out_channels
161
- self.use_conv_shortcut = conv_shortcut
162
-
163
- self.norm1 = Normalize(in_channels)
164
- self.conv1 = torch.nn.Conv2d(in_channels,
165
- out_channels,
166
- kernel_size=3,
167
- stride=1,
168
- padding=1)
169
- self.dcn1 = ModulatedDeformConvPack(out_channels,
170
- out_channels,
171
- kernel_size=3,
172
- stride=1,
173
- padding=1)
174
- if temb_channels > 0:
175
- self.temb_proj = torch.nn.Linear(temb_channels,
176
- out_channels)
177
- self.norm2 = Normalize(out_channels)
178
- self.dropout = torch.nn.Dropout(dropout)
179
- self.conv2 = torch.nn.Conv2d(out_channels,
180
- out_channels,
181
- kernel_size=3,
182
- stride=1,
183
- padding=1)
184
- self.dcn2 = ModulatedDeformConvPack(out_channels,
185
- out_channels,
186
- kernel_size=3,
187
- stride=1,
188
- padding=1)
189
-
190
- if self.in_channels != self.out_channels:
191
- if self.use_conv_shortcut:
192
- self.conv_shortcut = torch.nn.Conv2d(in_channels,
193
- out_channels,
194
- kernel_size=3,
195
- stride=1,
196
- padding=1)
197
- else:
198
- self.nin_shortcut = torch.nn.Conv2d(in_channels,
199
- out_channels,
200
- kernel_size=1,
201
- stride=1,
202
- padding=0)
203
-
204
- def forward(self, x,grayx, temb):
205
- h = x
206
- h = self.norm1(h)
207
- h = nonlinearity(h)
208
- h = self.conv1(h)
209
- h = self.dcn1(h,grayx)+h
210
-
211
- if temb is not None:
212
- h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
213
-
214
- h = self.norm2(h)
215
- h = nonlinearity(h)
216
- h = self.dropout(h)
217
- h = self.conv2(h)
218
- h = self.dcn2(h,grayx)+h
219
-
220
- if self.in_channels != self.out_channels:
221
- if self.use_conv_shortcut:
222
- x = self.conv_shortcut(x)
223
- else:
224
- x = self.nin_shortcut(x)
225
-
226
- return x+h
227
-
228
-
229
- class AttnBlock(nn.Module):
230
- def __init__(self, in_channels):
231
- super().__init__()
232
- self.in_channels = in_channels
233
-
234
- self.norm = Normalize(in_channels)
235
- self.q = torch.nn.Conv2d(in_channels,
236
- in_channels,
237
- kernel_size=1,
238
- stride=1,
239
- padding=0)
240
- self.k = torch.nn.Conv2d(in_channels,
241
- in_channels,
242
- kernel_size=1,
243
- stride=1,
244
- padding=0)
245
- self.v = torch.nn.Conv2d(in_channels,
246
- in_channels,
247
- kernel_size=1,
248
- stride=1,
249
- padding=0)
250
- self.proj_out = torch.nn.Conv2d(in_channels,
251
- in_channels,
252
- kernel_size=1,
253
- stride=1,
254
- padding=0)
255
-
256
- def forward(self, x):
257
- h_ = x
258
- h_ = self.norm(h_)
259
- q = self.q(h_)
260
- k = self.k(h_)
261
- v = self.v(h_)
262
-
263
- # compute attention
264
- b,c,h,w = q.shape
265
- q = q.reshape(b,c,h*w)
266
- q = q.permute(0,2,1) # b,hw,c
267
- k = k.reshape(b,c,h*w) # b,c,hw
268
- w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
269
- w_ = w_ * (int(c)**(-0.5))
270
- w_ = torch.nn.functional.softmax(w_, dim=2)
271
-
272
- # attend to values
273
- v = v.reshape(b,c,h*w)
274
- w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
275
- h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
276
- h_ = h_.reshape(b,c,h,w)
277
-
278
- h_ = self.proj_out(h_)
279
-
280
- return x+h_
281
-
282
- class MemoryEfficientAttnBlock(nn.Module):
283
- """
284
- Uses xformers efficient implementation,
285
- see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
286
- Note: this is a single-head self-attention operation
287
- """
288
- #
289
- def __init__(self, in_channels):
290
- super().__init__()
291
- self.in_channels = in_channels
292
-
293
- self.norm = Normalize(in_channels)
294
- self.q = torch.nn.Conv2d(in_channels,
295
- in_channels,
296
- kernel_size=1,
297
- stride=1,
298
- padding=0)
299
- self.k = torch.nn.Conv2d(in_channels,
300
- in_channels,
301
- kernel_size=1,
302
- stride=1,
303
- padding=0)
304
- self.v = torch.nn.Conv2d(in_channels,
305
- in_channels,
306
- kernel_size=1,
307
- stride=1,
308
- padding=0)
309
- self.proj_out = torch.nn.Conv2d(in_channels,
310
- in_channels,
311
- kernel_size=1,
312
- stride=1,
313
- padding=0)
314
- self.attention_op: Optional[Any] = None
315
-
316
- def forward(self, x):
317
- h_ = x
318
- h_ = self.norm(h_)
319
- q = self.q(h_)
320
- k = self.k(h_)
321
- v = self.v(h_)
322
-
323
- # compute attention
324
- B, C, H, W = q.shape
325
- q, k, v = map(lambda x: rearrange(x, 'b c h w -> b (h w) c'), (q, k, v))
326
-
327
- q, k, v = map(
328
- lambda t: t.unsqueeze(3)
329
- .reshape(B, t.shape[1], 1, C)
330
- .permute(0, 2, 1, 3)
331
- .reshape(B * 1, t.shape[1], C)
332
- .contiguous(),
333
- (q, k, v),
334
- )
335
- out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
336
-
337
- out = (
338
- out.unsqueeze(0)
339
- .reshape(B, 1, out.shape[1], C)
340
- .permute(0, 2, 1, 3)
341
- .reshape(B, out.shape[1], C)
342
- )
343
- out = rearrange(out, 'b (h w) c -> b c h w', b=B, h=H, w=W, c=C)
344
- out = self.proj_out(out)
345
- return x+out
346
-
347
-
348
- class MemoryEfficientCrossAttentionWrapper(MemoryEfficientCrossAttention):
349
- def forward(self, x, context=None, mask=None):
350
- b, c, h, w = x.shape
351
- x = rearrange(x, 'b c h w -> b (h w) c')
352
- out = super().forward(x, context=context, mask=mask)
353
- out = rearrange(out, 'b (h w) c -> b c h w', h=h, w=w, c=c)
354
- return x + out
355
-
356
-
357
- def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None):
358
- assert attn_type in ["vanilla", "vanilla-xformers", "memory-efficient-cross-attn", "linear", "none"], f'attn_type {attn_type} unknown'
359
- if XFORMERS_IS_AVAILBLE and attn_type == "vanilla":
360
- attn_type = "vanilla-xformers"
361
- print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
362
- if attn_type == "vanilla":
363
- assert attn_kwargs is None
364
- return AttnBlock(in_channels)
365
- elif attn_type == "vanilla-xformers":
366
- print(f"building MemoryEfficientAttnBlock with {in_channels} in_channels...")
367
- return MemoryEfficientAttnBlock(in_channels)
368
- elif type == "memory-efficient-cross-attn":
369
- attn_kwargs["query_dim"] = in_channels
370
- return MemoryEfficientCrossAttentionWrapper(**attn_kwargs)
371
- elif attn_type == "none":
372
- return nn.Identity(in_channels)
373
- else:
374
- raise NotImplementedError()
375
-
376
-
377
- class Model(nn.Module):
378
- def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
379
- attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
380
- resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
381
- super().__init__()
382
- if use_linear_attn: attn_type = "linear"
383
- self.ch = ch
384
- self.temb_ch = self.ch*4
385
- self.num_resolutions = len(ch_mult)
386
- self.num_res_blocks = num_res_blocks
387
- self.resolution = resolution
388
- self.in_channels = in_channels
389
-
390
- self.use_timestep = use_timestep
391
- if self.use_timestep:
392
- # timestep embedding
393
- self.temb = nn.Module()
394
- self.temb.dense = nn.ModuleList([
395
- torch.nn.Linear(self.ch,
396
- self.temb_ch),
397
- torch.nn.Linear(self.temb_ch,
398
- self.temb_ch),
399
- ])
400
-
401
- # downsampling
402
- self.conv_in = torch.nn.Conv2d(in_channels,
403
- self.ch,
404
- kernel_size=3,
405
- stride=1,
406
- padding=1)
407
-
408
- curr_res = resolution
409
- in_ch_mult = (1,)+tuple(ch_mult)
410
- self.down = nn.ModuleList()
411
- for i_level in range(self.num_resolutions):
412
- block = nn.ModuleList()
413
- attn = nn.ModuleList()
414
- block_in = ch*in_ch_mult[i_level]
415
- block_out = ch*ch_mult[i_level]
416
- for i_block in range(self.num_res_blocks):
417
- block.append(ResnetBlock(in_channels=block_in,
418
- out_channels=block_out,
419
- temb_channels=self.temb_ch,
420
- dropout=dropout))
421
- block_in = block_out
422
- if curr_res in attn_resolutions:
423
- attn.append(make_attn(block_in, attn_type=attn_type))
424
- down = nn.Module()
425
- down.block = block
426
- down.attn = attn
427
- if i_level != self.num_resolutions-1:
428
- down.downsample = Downsample(block_in, resamp_with_conv)
429
- curr_res = curr_res // 2
430
- self.down.append(down)
431
-
432
- # middle
433
- self.mid = nn.Module()
434
- self.mid.block_1 = ResnetBlock(in_channels=block_in,
435
- out_channels=block_in,
436
- temb_channels=self.temb_ch,
437
- dropout=dropout)
438
- self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
439
- self.mid.block_2 = ResnetBlock(in_channels=block_in,
440
- out_channels=block_in,
441
- temb_channels=self.temb_ch,
442
- dropout=dropout)
443
-
444
- # upsampling
445
- self.up = nn.ModuleList()
446
- for i_level in reversed(range(self.num_resolutions)):
447
- block = nn.ModuleList()
448
- attn = nn.ModuleList()
449
- block_out = ch*ch_mult[i_level]
450
- skip_in = ch*ch_mult[i_level]
451
- for i_block in range(self.num_res_blocks+1):
452
- if i_block == self.num_res_blocks:
453
- skip_in = ch*in_ch_mult[i_level]
454
- block.append(ResnetBlock(in_channels=block_in+skip_in,
455
- out_channels=block_out,
456
- temb_channels=self.temb_ch,
457
- dropout=dropout))
458
- block_in = block_out
459
- if curr_res in attn_resolutions:
460
- attn.append(make_attn(block_in, attn_type=attn_type))
461
- up = nn.Module()
462
- up.block = block
463
- up.attn = attn
464
- if i_level != 0:
465
- up.upsample = Upsample(block_in, resamp_with_conv)
466
- curr_res = curr_res * 2
467
- self.up.insert(0, up) # prepend to get consistent order
468
-
469
- # end
470
- self.norm_out = Normalize(block_in)
471
- self.conv_out = torch.nn.Conv2d(block_in,
472
- out_ch,
473
- kernel_size=3,
474
- stride=1,
475
- padding=1)
476
-
477
- def forward(self, x, t=None, context=None):
478
- #assert x.shape[2] == x.shape[3] == self.resolution
479
- if context is not None:
480
- # assume aligned context, cat along channel axis
481
- x = torch.cat((x, context), dim=1)
482
- if self.use_timestep:
483
- # timestep embedding
484
- assert t is not None
485
- temb = get_timestep_embedding(t, self.ch)
486
- temb = self.temb.dense[0](temb)
487
- temb = nonlinearity(temb)
488
- temb = self.temb.dense[1](temb)
489
- else:
490
- temb = None
491
-
492
- # downsampling
493
- hs = [self.conv_in(x)]
494
- for i_level in range(self.num_resolutions):
495
- for i_block in range(self.num_res_blocks):
496
- h = self.down[i_level].block[i_block](hs[-1], temb)
497
- if len(self.down[i_level].attn) > 0:
498
- h = self.down[i_level].attn[i_block](h)
499
- hs.append(h)
500
- if i_level != self.num_resolutions-1:
501
- hs.append(self.down[i_level].downsample(hs[-1]))
502
-
503
- # middle
504
- h = hs[-1]
505
- h = self.mid.block_1(h, temb)
506
- h = self.mid.attn_1(h)
507
- h = self.mid.block_2(h, temb)
508
-
509
- # upsampling
510
- for i_level in reversed(range(self.num_resolutions)):
511
- for i_block in range(self.num_res_blocks+1):
512
- h = self.up[i_level].block[i_block](
513
- torch.cat([h, hs.pop()], dim=1), temb)
514
- if len(self.up[i_level].attn) > 0:
515
- h = self.up[i_level].attn[i_block](h)
516
- if i_level != 0:
517
- h = self.up[i_level].upsample(h)
518
-
519
- # end
520
- h = self.norm_out(h)
521
- h = nonlinearity(h)
522
- h = self.conv_out(h)
523
- return h
524
-
525
- def get_last_layer(self):
526
- return self.conv_out.weight
527
-
528
-
529
- class Encoder(nn.Module):
530
- def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
531
- attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
532
- resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
533
- **ignore_kwargs):
534
- super().__init__()
535
- if use_linear_attn: attn_type = "linear"
536
- self.ch = ch
537
- self.temb_ch = 0
538
- self.num_resolutions = len(ch_mult)
539
- self.num_res_blocks = num_res_blocks
540
- self.resolution = resolution
541
- self.in_channels = in_channels
542
-
543
- # downsampling
544
- self.conv_in = torch.nn.Conv2d(in_channels,
545
- self.ch,
546
- kernel_size=3,
547
- stride=1,
548
- padding=1)
549
-
550
- curr_res = resolution
551
- in_ch_mult = (1,)+tuple(ch_mult)
552
- self.in_ch_mult = in_ch_mult
553
- self.down = nn.ModuleList()
554
- for i_level in range(self.num_resolutions):
555
- block = nn.ModuleList()
556
- attn = nn.ModuleList()
557
- block_in = ch*in_ch_mult[i_level]
558
- block_out = ch*ch_mult[i_level]
559
- for i_block in range(self.num_res_blocks):
560
- block.append(ResnetBlock(in_channels=block_in,
561
- out_channels=block_out,
562
- temb_channels=self.temb_ch,
563
- dropout=dropout))
564
- block_in = block_out
565
- if curr_res in attn_resolutions:
566
- attn.append(make_attn(block_in, attn_type=attn_type))
567
- down = nn.Module()
568
- down.block = block
569
- down.attn = attn
570
- if i_level != self.num_resolutions-1:
571
- down.downsample = Downsample(block_in, resamp_with_conv)
572
- curr_res = curr_res // 2
573
- self.down.append(down)
574
-
575
- # middle
576
- self.mid = nn.Module()
577
- self.mid.block_1 = ResnetBlock(in_channels=block_in,
578
- out_channels=block_in,
579
- temb_channels=self.temb_ch,
580
- dropout=dropout)
581
- self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
582
- self.mid.block_2 = ResnetBlock(in_channels=block_in,
583
- out_channels=block_in,
584
- temb_channels=self.temb_ch,
585
- dropout=dropout)
586
-
587
- # end
588
- self.norm_out = Normalize(block_in)
589
- self.conv_out = torch.nn.Conv2d(block_in,
590
- 2*z_channels if double_z else z_channels,
591
- kernel_size=3,
592
- stride=1,
593
- padding=1)
594
-
595
- def forward(self, x):
596
- # timestep embedding
597
- temb = None
598
-
599
- # downsampling
600
- hs = [self.conv_in(x)]
601
- for i_level in range(self.num_resolutions):
602
- for i_block in range(self.num_res_blocks):
603
- h = self.down[i_level].block[i_block](hs[-1], temb)
604
- if len(self.down[i_level].attn) > 0:
605
- h = self.down[i_level].attn[i_block](h)
606
- hs.append(h)
607
- if i_level != self.num_resolutions-1:
608
- hs.append(self.down[i_level].downsample(hs[-1]))
609
-
610
- # middle
611
- h = hs[-1]
612
- h = self.mid.block_1(h, temb)
613
- h = self.mid.attn_1(h)
614
- h = self.mid.block_2(h, temb)
615
-
616
- # end
617
- h = self.norm_out(h)
618
- h = nonlinearity(h)
619
- h = self.conv_out(h)
620
- return h
621
-
622
- class ModulatedDeformConv(nn.Module):
623
-
624
- def __init__(self,
625
- in_channels,
626
- out_channels,
627
- kernel_size,
628
- stride=1,
629
- padding=0,
630
- dilation=1,
631
- groups=1,
632
- deformable_groups=1,
633
- bias=True):
634
- super(ModulatedDeformConv, self).__init__()
635
- self.in_channels = in_channels
636
- self.out_channels = out_channels
637
- self.kernel_size = _pair(kernel_size)
638
- self.stride = stride
639
- self.padding = padding
640
- self.dilation = dilation
641
- self.groups = groups
642
- self.deformable_groups = deformable_groups
643
- self.with_bias = bias
644
- # enable compatibility with nn.Conv2d
645
- self.transposed = False
646
- self.output_padding = _single(0)
647
-
648
- self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, *self.kernel_size))
649
- if bias:
650
- self.bias = nn.Parameter(torch.Tensor(out_channels))
651
- else:
652
- self.register_parameter('bias', None)
653
- self.init_weights()
654
-
655
- def init_weights(self):
656
- n = self.in_channels
657
- for k in self.kernel_size:
658
- n *= k
659
- stdv = 1. / math.sqrt(n)
660
- self.weight.data.uniform_(-stdv, stdv)
661
- if self.bias is not None:
662
- self.bias.data.zero_()
663
-
664
- # def forward(self, x, offset, mask):
665
- # return torchvision.ops.con(x, offset, mask, self.weight, self.bias, self.stride, self.padding, self.dilation,
666
- # self.groups, self.deformable_groups)
667
-
668
-
669
- class ModulatedDeformConvPack(ModulatedDeformConv):
670
- """A ModulatedDeformable Conv Encapsulation that acts as normal Conv layers.
671
-
672
- Args:
673
- in_channels (int): Same as nn.Conv2d.
674
- out_channels (int): Same as nn.Conv2d.
675
- kernel_size (int or tuple[int]): Same as nn.Conv2d.
676
- stride (int or tuple[int]): Same as nn.Conv2d.
677
- padding (int or tuple[int]): Same as nn.Conv2d.
678
- dilation (int or tuple[int]): Same as nn.Conv2d.
679
- groups (int): Same as nn.Conv2d.
680
- bias (bool or str): If specified as `auto`, it will be decided by the
681
- norm_cfg. Bias will be set as True if norm_cfg is None, otherwise
682
- False.
683
- """
684
-
685
- _version = 2
686
-
687
- def __init__(self, *args, **kwargs):
688
- super(ModulatedDeformConvPack, self).__init__(*args, **kwargs)
689
-
690
- self.conv_offset = nn.Conv2d(
691
- self.in_channels+4,
692
- self.deformable_groups * 3 * self.kernel_size[0] * self.kernel_size[1],
693
- kernel_size=self.kernel_size,
694
- stride=_pair(self.stride),
695
- padding=_pair(self.padding),
696
- dilation=_pair(self.dilation),
697
- bias=True)
698
- self.init_weights()
699
-
700
- def init_weights(self):
701
- super(ModulatedDeformConvPack, self).init_weights()
702
- if hasattr(self, 'conv_offset'):
703
- self.conv_offset.weight.data.zero_()
704
- self.conv_offset.bias.data.zero_()
705
-
706
- def forward(self, x, gray_content):
707
- out = self.conv_offset(torch.cat((x,gray_content),dim=1))
708
- o1, o2, mask = torch.chunk(out, 3, dim=1)
709
- offset = torch.cat((o1, o2), dim=1)
710
- mask = torch.sigmoid(mask)
711
-
712
- # return modulated_deform_conv(x, offset, mask, self.weight, self.bias, self.stride, self.padding, self.dilation,
713
- # self.groups, self.deformable_groups)
714
- return torchvision.ops.deform_conv2d(x, offset, self.weight, self.bias, self.stride, self.padding,
715
- self.dilation, mask)
716
-
717
-
718
- # class SecondOrderDeformableAlignment(ModulatedDeformConvPack):
719
- # """Second-order deformable alignment module.
720
-
721
- # Args:
722
- # in_channels (int): Same as nn.Conv2d.
723
- # out_channels (int): Same as nn.Conv2d.
724
- # kernel_size (int or tuple[int]): Same as nn.Conv2d.
725
- # stride (int or tuple[int]): Same as nn.Conv2d.
726
- # padding (int or tuple[int]): Same as nn.Conv2d.
727
- # dilation (int or tuple[int]): Same as nn.Conv2d.
728
- # groups (int): Same as nn.Conv2d.
729
- # bias (bool or str): If specified as `auto`, it will be decided by the
730
- # norm_cfg. Bias will be set as True if norm_cfg is None, otherwise
731
- # False.
732
- # max_residue_magnitude (int): The maximum magnitude of the offset
733
- # residue (Eq. 6 in paper). Default: 10.
734
- # """
735
-
736
- # def __init__(self, *args, **kwargs):
737
- # self.max_residue_magnitude = kwargs.pop('max_residue_magnitude', 10)
738
-
739
- # super(SecondOrderDeformableAlignment, self).__init__(*args, **kwargs)
740
-
741
- # self.conv_offset = nn.Sequential(
742
- # nn.Conv2d(3 * self.out_channels + 4, self.out_channels, 3, 1, 1),
743
- # nn.LeakyReLU(negative_slope=0.1, inplace=True),
744
- # nn.Conv2d(self.out_channels, self.out_channels, 3, 1, 1),
745
- # nn.LeakyReLU(negative_slope=0.1, inplace=True),
746
- # nn.Conv2d(self.out_channels, self.out_channels, 3, 1, 1),
747
- # nn.LeakyReLU(negative_slope=0.1, inplace=True),
748
- # nn.Conv2d(self.out_channels, 27 * self.deformable_groups, 3, 1, 1),
749
- # )
750
-
751
- # self.init_offset()
752
-
753
- # def init_offset(self):
754
-
755
- # def _constant_init(module, val, bias=0):
756
- # if hasattr(module, 'weight') and module.weight is not None:
757
- # nn.init.constant_(module.weight, val)
758
- # if hasattr(module, 'bias') and module.bias is not None:
759
- # nn.init.constant_(module.bias, bias)
760
-
761
- # _constant_init(self.conv_offset[-1], val=0, bias=0)
762
-
763
- # def forward(self, x, extra_feat, flow_1, flow_2):
764
- # extra_feat = torch.cat([extra_feat, flow_1, flow_2], dim=1)
765
- # out = self.conv_offset(extra_feat)
766
- # o1, o2, mask = torch.chunk(out, 3, dim=1)
767
-
768
- # # offset
769
- # offset = self.max_residue_magnitude * torch.tanh(torch.cat((o1, o2), dim=1))
770
- # offset_1, offset_2 = torch.chunk(offset, 2, dim=1)
771
- # offset_1 = offset_1 + flow_1.flip(1).repeat(1, offset_1.size(1) // 2, 1, 1)
772
- # offset_2 = offset_2 + flow_2.flip(1).repeat(1, offset_2.size(1) // 2, 1, 1)
773
- # offset = torch.cat([offset_1, offset_2], dim=1)
774
-
775
- # # mask
776
- # mask = torch.sigmoid(mask)
777
-
778
- # return torchvision.ops.deform_conv2d(x, offset, self.weight, self.bias, self.stride, self.padding,
779
- # self.dilation, mask)
780
-
781
- class Decoder(nn.Module):
782
- def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
783
- attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
784
- resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
785
- attn_type="vanilla", **ignorekwargs):
786
- super().__init__()
787
- if use_linear_attn: attn_type = "linear"
788
- self.ch = ch
789
- self.temb_ch = 0
790
- self.num_resolutions = len(ch_mult)
791
- self.num_res_blocks = num_res_blocks
792
- self.resolution = resolution
793
- self.in_channels = in_channels
794
- self.give_pre_end = give_pre_end
795
- self.tanh_out = tanh_out
796
-
797
- # compute in_ch_mult, block_in and curr_res at lowest res
798
- in_ch_mult = (1,)+tuple(ch_mult)
799
- block_in = ch*ch_mult[self.num_resolutions-1]
800
- curr_res = resolution // 2**(self.num_resolutions-1)
801
- self.z_shape = (1,z_channels,curr_res,curr_res)
802
- print("Working with z of shape {} = {} dimensions.".format(
803
- self.z_shape, np.prod(self.z_shape)))
804
-
805
- # z to block_in
806
- self.conv_in = torch.nn.Conv2d(z_channels,
807
- block_in,
808
- kernel_size=3,
809
- stride=1,
810
- padding=1)
811
-
812
- self.dcn_in = ModulatedDeformConvPack(block_in,
813
- block_in,
814
- kernel_size=3,
815
- stride=1,
816
- padding=1)
817
- # middle
818
- self.mid = nn.Module()
819
- self.mid.block_1 = ResnetBlock_dcn(in_channels=block_in,
820
- out_channels=block_in,
821
- temb_channels=self.temb_ch,
822
- dropout=dropout)
823
- self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
824
- self.mid.block_2 = ResnetBlock_dcn(in_channels=block_in,
825
- out_channels=block_in,
826
- temb_channels=self.temb_ch,
827
- dropout=dropout)
828
-
829
- # upsampling
830
- self.up = nn.ModuleList()
831
- for i_level in reversed(range(self.num_resolutions)):
832
- block = nn.ModuleList()
833
- attn = nn.ModuleList()
834
- block_out = ch*ch_mult[i_level]
835
- for i_block in range(self.num_res_blocks+1):
836
- block.append(ResnetBlock(in_channels=block_in,
837
- out_channels=block_out,
838
- temb_channels=self.temb_ch,
839
- dropout=dropout))
840
- # else:
841
- # block.append(ResnetBlock_dcn(in_channels=block_in,
842
- # out_channels=block_out,
843
- # temb_channels=self.temb_ch,
844
- # dropout=dropout))
845
- block_in = block_out
846
- if curr_res in attn_resolutions:
847
- attn.append(make_attn(block_in, attn_type=attn_type))
848
- up = nn.Module()
849
- up.block = block
850
- up.attn = attn
851
- if i_level != 0:
852
- up.upsample = Upsample(block_in, resamp_with_conv)
853
- curr_res = curr_res * 2
854
- self.up.insert(0, up) # prepend to get consistent order
855
-
856
- # end
857
- self.norm_out = Normalize(block_in)
858
- self.conv_out = torch.nn.Conv2d(block_in,
859
- out_ch,
860
- kernel_size=3,
861
- stride=1,
862
- padding=1)
863
- # self.dcn_out = ModulatedDeformConvPack(out_ch,
864
- # out_ch,
865
- # kernel_size=3,
866
- # stride=1,
867
- # padding=1)
868
-
869
- def forward(self, z, gray_content_z):
870
- #assert z.shape[1:] == self.z_shape[1:]
871
- self.last_z_shape = z.shape
872
-
873
- # timestep embedding
874
- temb = None
875
-
876
- # z to block_in
877
- h = self.conv_in(z)
878
- # print("h",h.shape)
879
- # print("gray_content_z",gray_content_z.shape)
880
- h = self.dcn_in(h, gray_content_z)+h
881
-
882
- # middle
883
- h = self.mid.block_1(h, gray_content_z,temb)
884
- h = self.mid.attn_1(h)
885
- h = self.mid.block_2(h, gray_content_z,temb)
886
-
887
- # upsampling
888
- for i_level in reversed(range(self.num_resolutions)):
889
- for i_block in range(self.num_res_blocks+1):
890
- h = self.up[i_level].block[i_block](h, temb)#h, gray_content_z,temb
891
- if len(self.up[i_level].attn) > 0:
892
- h = self.up[i_level].attn[i_block](h)
893
- if i_level != 0:
894
- h = self.up[i_level].upsample(h)
895
-
896
- # end
897
- if self.give_pre_end:
898
- return h
899
-
900
- h = self.norm_out(h)
901
- h = nonlinearity(h)
902
- h = self.conv_out(h)
903
- # print(h.shape)
904
- # h = self.dcn_out(h,gray_content_z)
905
- if self.tanh_out:
906
- h = torch.tanh(h)
907
- return h
908
-
909
-
910
- class SimpleDecoder(nn.Module):
911
- def __init__(self, in_channels, out_channels, *args, **kwargs):
912
- super().__init__()
913
- self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
914
- ResnetBlock(in_channels=in_channels,
915
- out_channels=2 * in_channels,
916
- temb_channels=0, dropout=0.0),
917
- ResnetBlock(in_channels=2 * in_channels,
918
- out_channels=4 * in_channels,
919
- temb_channels=0, dropout=0.0),
920
- ResnetBlock(in_channels=4 * in_channels,
921
- out_channels=2 * in_channels,
922
- temb_channels=0, dropout=0.0),
923
- nn.Conv2d(2*in_channels, in_channels, 1),
924
- Upsample(in_channels, with_conv=True)])
925
- # end
926
- self.norm_out = Normalize(in_channels)
927
- self.conv_out = torch.nn.Conv2d(in_channels,
928
- out_channels,
929
- kernel_size=3,
930
- stride=1,
931
- padding=1)
932
-
933
- def forward(self, x):
934
- for i, layer in enumerate(self.model):
935
- if i in [1,2,3]:
936
- x = layer(x, None)
937
- else:
938
- x = layer(x)
939
-
940
- h = self.norm_out(x)
941
- h = nonlinearity(h)
942
- x = self.conv_out(h)
943
- return x
944
-
945
-
946
- class UpsampleDecoder(nn.Module):
947
- def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
948
- ch_mult=(2,2), dropout=0.0):
949
- super().__init__()
950
- # upsampling
951
- self.temb_ch = 0
952
- self.num_resolutions = len(ch_mult)
953
- self.num_res_blocks = num_res_blocks
954
- block_in = in_channels
955
- curr_res = resolution // 2 ** (self.num_resolutions - 1)
956
- self.res_blocks = nn.ModuleList()
957
- self.upsample_blocks = nn.ModuleList()
958
- for i_level in range(self.num_resolutions):
959
- res_block = []
960
- block_out = ch * ch_mult[i_level]
961
- for i_block in range(self.num_res_blocks + 1):
962
- res_block.append(ResnetBlock(in_channels=block_in,
963
- out_channels=block_out,
964
- temb_channels=self.temb_ch,
965
- dropout=dropout))
966
- block_in = block_out
967
- self.res_blocks.append(nn.ModuleList(res_block))
968
- if i_level != self.num_resolutions - 1:
969
- self.upsample_blocks.append(Upsample(block_in, True))
970
- curr_res = curr_res * 2
971
-
972
- # end
973
- self.norm_out = Normalize(block_in)
974
- self.conv_out = torch.nn.Conv2d(block_in,
975
- out_channels,
976
- kernel_size=3,
977
- stride=1,
978
- padding=1)
979
-
980
- def forward(self, x):
981
- # upsampling
982
- h = x
983
- for k, i_level in enumerate(range(self.num_resolutions)):
984
- for i_block in range(self.num_res_blocks + 1):
985
- h = self.res_blocks[i_level][i_block](h, None)
986
- if i_level != self.num_resolutions - 1:
987
- h = self.upsample_blocks[k](h)
988
- h = self.norm_out(h)
989
- h = nonlinearity(h)
990
- h = self.conv_out(h)
991
- return h
992
-
993
-
994
- class LatentRescaler(nn.Module):
995
- def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
996
- super().__init__()
997
- # residual block, interpolate, residual block
998
- self.factor = factor
999
- self.conv_in = nn.Conv2d(in_channels,
1000
- mid_channels,
1001
- kernel_size=3,
1002
- stride=1,
1003
- padding=1)
1004
- self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
1005
- out_channels=mid_channels,
1006
- temb_channels=0,
1007
- dropout=0.0) for _ in range(depth)])
1008
- self.attn = AttnBlock(mid_channels)
1009
- self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
1010
- out_channels=mid_channels,
1011
- temb_channels=0,
1012
- dropout=0.0) for _ in range(depth)])
1013
-
1014
- self.conv_out = nn.Conv2d(mid_channels,
1015
- out_channels,
1016
- kernel_size=1,
1017
- )
1018
-
1019
- def forward(self, x):
1020
- x = self.conv_in(x)
1021
- for block in self.res_block1:
1022
- x = block(x, None)
1023
- x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
1024
- x = self.attn(x)
1025
- for block in self.res_block2:
1026
- x = block(x, None)
1027
- x = self.conv_out(x)
1028
- return x
1029
-
1030
-
1031
- class MergedRescaleEncoder(nn.Module):
1032
- def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
1033
- attn_resolutions, dropout=0.0, resamp_with_conv=True,
1034
- ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
1035
- super().__init__()
1036
- intermediate_chn = ch * ch_mult[-1]
1037
- self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
1038
- z_channels=intermediate_chn, double_z=False, resolution=resolution,
1039
- attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
1040
- out_ch=None)
1041
- self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
1042
- mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
1043
-
1044
- def forward(self, x):
1045
- x = self.encoder(x)
1046
- x = self.rescaler(x)
1047
- return x
1048
-
1049
-
1050
- class MergedRescaleDecoder(nn.Module):
1051
- def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
1052
- dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
1053
- super().__init__()
1054
- tmp_chn = z_channels*ch_mult[-1]
1055
- self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
1056
- resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
1057
- ch_mult=ch_mult, resolution=resolution, ch=ch)
1058
- self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
1059
- out_channels=tmp_chn, depth=rescale_module_depth)
1060
-
1061
- def forward(self, x):
1062
- x = self.rescaler(x)
1063
- x = self.decoder(x)
1064
- return x
1065
-
1066
-
1067
- class Upsampler(nn.Module):
1068
- def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
1069
- super().__init__()
1070
- assert out_size >= in_size
1071
- num_blocks = int(np.log2(out_size//in_size))+1
1072
- factor_up = 1.+ (out_size % in_size)
1073
- print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
1074
- self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
1075
- out_channels=in_channels)
1076
- self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
1077
- attn_resolutions=[], in_channels=None, ch=in_channels,
1078
- ch_mult=[ch_mult for _ in range(num_blocks)])
1079
-
1080
- def forward(self, x):
1081
- x = self.rescaler(x)
1082
- x = self.decoder(x)
1083
- return x
1084
-
1085
-
1086
- class Resize(nn.Module):
1087
- def __init__(self, in_channels=None, learned=False, mode="bilinear"):
1088
- super().__init__()
1089
- self.with_conv = learned
1090
- self.mode = mode
1091
- if self.with_conv:
1092
- print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
1093
- raise NotImplementedError()
1094
- assert in_channels is not None
1095
- # no asymmetric padding in torch conv, must do it ourselves
1096
- self.conv = torch.nn.Conv2d(in_channels,
1097
- in_channels,
1098
- kernel_size=4,
1099
- stride=2,
1100
- padding=1)
1101
-
1102
- def forward(self, x, scale_factor=1.0):
1103
- if scale_factor==1.0:
1104
- return x
1105
- else:
1106
- x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
1107
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/modules/diffusionmodules/model_brefore_dcn.py DELETED
@@ -1,852 +0,0 @@
1
- # pytorch_diffusion + derived encoder decoder
2
- import math
3
- import torch
4
- import torch.nn as nn
5
- import numpy as np
6
- from einops import rearrange
7
- from typing import Optional, Any
8
-
9
- from ldm.modules.attention import MemoryEfficientCrossAttention
10
-
11
- try:
12
- import xformers
13
- import xformers.ops
14
- XFORMERS_IS_AVAILBLE = True
15
- except:
16
- XFORMERS_IS_AVAILBLE = False
17
- print("No module 'xformers'. Proceeding without it.")
18
-
19
-
20
- def get_timestep_embedding(timesteps, embedding_dim):
21
- """
22
- This matches the implementation in Denoising Diffusion Probabilistic Models:
23
- From Fairseq.
24
- Build sinusoidal embeddings.
25
- This matches the implementation in tensor2tensor, but differs slightly
26
- from the description in Section 3.5 of "Attention Is All You Need".
27
- """
28
- assert len(timesteps.shape) == 1
29
-
30
- half_dim = embedding_dim // 2
31
- emb = math.log(10000) / (half_dim - 1)
32
- emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
33
- emb = emb.to(device=timesteps.device)
34
- emb = timesteps.float()[:, None] * emb[None, :]
35
- emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
36
- if embedding_dim % 2 == 1: # zero pad
37
- emb = torch.nn.functional.pad(emb, (0,1,0,0))
38
- return emb
39
-
40
-
41
- def nonlinearity(x):
42
- # swish
43
- return x*torch.sigmoid(x)
44
-
45
-
46
- def Normalize(in_channels, num_groups=32):
47
- return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
48
-
49
-
50
- class Upsample(nn.Module):
51
- def __init__(self, in_channels, with_conv):
52
- super().__init__()
53
- self.with_conv = with_conv
54
- if self.with_conv:
55
- self.conv = torch.nn.Conv2d(in_channels,
56
- in_channels,
57
- kernel_size=3,
58
- stride=1,
59
- padding=1)
60
-
61
- def forward(self, x):
62
- x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
63
- if self.with_conv:
64
- x = self.conv(x)
65
- return x
66
-
67
-
68
- class Downsample(nn.Module):
69
- def __init__(self, in_channels, with_conv):
70
- super().__init__()
71
- self.with_conv = with_conv
72
- if self.with_conv:
73
- # no asymmetric padding in torch conv, must do it ourselves
74
- self.conv = torch.nn.Conv2d(in_channels,
75
- in_channels,
76
- kernel_size=3,
77
- stride=2,
78
- padding=0)
79
-
80
- def forward(self, x):
81
- if self.with_conv:
82
- pad = (0,1,0,1)
83
- x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
84
- x = self.conv(x)
85
- else:
86
- x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
87
- return x
88
-
89
-
90
- class ResnetBlock(nn.Module):
91
- def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
92
- dropout, temb_channels=512):
93
- super().__init__()
94
- self.in_channels = in_channels
95
- out_channels = in_channels if out_channels is None else out_channels
96
- self.out_channels = out_channels
97
- self.use_conv_shortcut = conv_shortcut
98
-
99
- self.norm1 = Normalize(in_channels)
100
- self.conv1 = torch.nn.Conv2d(in_channels,
101
- out_channels,
102
- kernel_size=3,
103
- stride=1,
104
- padding=1)
105
- if temb_channels > 0:
106
- self.temb_proj = torch.nn.Linear(temb_channels,
107
- out_channels)
108
- self.norm2 = Normalize(out_channels)
109
- self.dropout = torch.nn.Dropout(dropout)
110
- self.conv2 = torch.nn.Conv2d(out_channels,
111
- out_channels,
112
- kernel_size=3,
113
- stride=1,
114
- padding=1)
115
- if self.in_channels != self.out_channels:
116
- if self.use_conv_shortcut:
117
- self.conv_shortcut = torch.nn.Conv2d(in_channels,
118
- out_channels,
119
- kernel_size=3,
120
- stride=1,
121
- padding=1)
122
- else:
123
- self.nin_shortcut = torch.nn.Conv2d(in_channels,
124
- out_channels,
125
- kernel_size=1,
126
- stride=1,
127
- padding=0)
128
-
129
- def forward(self, x, temb):
130
- h = x
131
- h = self.norm1(h)
132
- h = nonlinearity(h)
133
- h = self.conv1(h)
134
-
135
- if temb is not None:
136
- h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
137
-
138
- h = self.norm2(h)
139
- h = nonlinearity(h)
140
- h = self.dropout(h)
141
- h = self.conv2(h)
142
-
143
- if self.in_channels != self.out_channels:
144
- if self.use_conv_shortcut:
145
- x = self.conv_shortcut(x)
146
- else:
147
- x = self.nin_shortcut(x)
148
-
149
- return x+h
150
-
151
-
152
- class AttnBlock(nn.Module):
153
- def __init__(self, in_channels):
154
- super().__init__()
155
- self.in_channels = in_channels
156
-
157
- self.norm = Normalize(in_channels)
158
- self.q = torch.nn.Conv2d(in_channels,
159
- in_channels,
160
- kernel_size=1,
161
- stride=1,
162
- padding=0)
163
- self.k = torch.nn.Conv2d(in_channels,
164
- in_channels,
165
- kernel_size=1,
166
- stride=1,
167
- padding=0)
168
- self.v = torch.nn.Conv2d(in_channels,
169
- in_channels,
170
- kernel_size=1,
171
- stride=1,
172
- padding=0)
173
- self.proj_out = torch.nn.Conv2d(in_channels,
174
- in_channels,
175
- kernel_size=1,
176
- stride=1,
177
- padding=0)
178
-
179
- def forward(self, x):
180
- h_ = x
181
- h_ = self.norm(h_)
182
- q = self.q(h_)
183
- k = self.k(h_)
184
- v = self.v(h_)
185
-
186
- # compute attention
187
- b,c,h,w = q.shape
188
- q = q.reshape(b,c,h*w)
189
- q = q.permute(0,2,1) # b,hw,c
190
- k = k.reshape(b,c,h*w) # b,c,hw
191
- w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
192
- w_ = w_ * (int(c)**(-0.5))
193
- w_ = torch.nn.functional.softmax(w_, dim=2)
194
-
195
- # attend to values
196
- v = v.reshape(b,c,h*w)
197
- w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
198
- h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
199
- h_ = h_.reshape(b,c,h,w)
200
-
201
- h_ = self.proj_out(h_)
202
-
203
- return x+h_
204
-
205
- class MemoryEfficientAttnBlock(nn.Module):
206
- """
207
- Uses xformers efficient implementation,
208
- see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
209
- Note: this is a single-head self-attention operation
210
- """
211
- #
212
- def __init__(self, in_channels):
213
- super().__init__()
214
- self.in_channels = in_channels
215
-
216
- self.norm = Normalize(in_channels)
217
- self.q = torch.nn.Conv2d(in_channels,
218
- in_channels,
219
- kernel_size=1,
220
- stride=1,
221
- padding=0)
222
- self.k = torch.nn.Conv2d(in_channels,
223
- in_channels,
224
- kernel_size=1,
225
- stride=1,
226
- padding=0)
227
- self.v = torch.nn.Conv2d(in_channels,
228
- in_channels,
229
- kernel_size=1,
230
- stride=1,
231
- padding=0)
232
- self.proj_out = torch.nn.Conv2d(in_channels,
233
- in_channels,
234
- kernel_size=1,
235
- stride=1,
236
- padding=0)
237
- self.attention_op: Optional[Any] = None
238
-
239
- def forward(self, x):
240
- h_ = x
241
- h_ = self.norm(h_)
242
- q = self.q(h_)
243
- k = self.k(h_)
244
- v = self.v(h_)
245
-
246
- # compute attention
247
- B, C, H, W = q.shape
248
- q, k, v = map(lambda x: rearrange(x, 'b c h w -> b (h w) c'), (q, k, v))
249
-
250
- q, k, v = map(
251
- lambda t: t.unsqueeze(3)
252
- .reshape(B, t.shape[1], 1, C)
253
- .permute(0, 2, 1, 3)
254
- .reshape(B * 1, t.shape[1], C)
255
- .contiguous(),
256
- (q, k, v),
257
- )
258
- out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
259
-
260
- out = (
261
- out.unsqueeze(0)
262
- .reshape(B, 1, out.shape[1], C)
263
- .permute(0, 2, 1, 3)
264
- .reshape(B, out.shape[1], C)
265
- )
266
- out = rearrange(out, 'b (h w) c -> b c h w', b=B, h=H, w=W, c=C)
267
- out = self.proj_out(out)
268
- return x+out
269
-
270
-
271
- class MemoryEfficientCrossAttentionWrapper(MemoryEfficientCrossAttention):
272
- def forward(self, x, context=None, mask=None):
273
- b, c, h, w = x.shape
274
- x = rearrange(x, 'b c h w -> b (h w) c')
275
- out = super().forward(x, context=context, mask=mask)
276
- out = rearrange(out, 'b (h w) c -> b c h w', h=h, w=w, c=c)
277
- return x + out
278
-
279
-
280
- def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None):
281
- assert attn_type in ["vanilla", "vanilla-xformers", "memory-efficient-cross-attn", "linear", "none"], f'attn_type {attn_type} unknown'
282
- if XFORMERS_IS_AVAILBLE and attn_type == "vanilla":
283
- attn_type = "vanilla-xformers"
284
- print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
285
- if attn_type == "vanilla":
286
- assert attn_kwargs is None
287
- return AttnBlock(in_channels)
288
- elif attn_type == "vanilla-xformers":
289
- print(f"building MemoryEfficientAttnBlock with {in_channels} in_channels...")
290
- return MemoryEfficientAttnBlock(in_channels)
291
- elif type == "memory-efficient-cross-attn":
292
- attn_kwargs["query_dim"] = in_channels
293
- return MemoryEfficientCrossAttentionWrapper(**attn_kwargs)
294
- elif attn_type == "none":
295
- return nn.Identity(in_channels)
296
- else:
297
- raise NotImplementedError()
298
-
299
-
300
- class Model(nn.Module):
301
- def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
302
- attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
303
- resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
304
- super().__init__()
305
- if use_linear_attn: attn_type = "linear"
306
- self.ch = ch
307
- self.temb_ch = self.ch*4
308
- self.num_resolutions = len(ch_mult)
309
- self.num_res_blocks = num_res_blocks
310
- self.resolution = resolution
311
- self.in_channels = in_channels
312
-
313
- self.use_timestep = use_timestep
314
- if self.use_timestep:
315
- # timestep embedding
316
- self.temb = nn.Module()
317
- self.temb.dense = nn.ModuleList([
318
- torch.nn.Linear(self.ch,
319
- self.temb_ch),
320
- torch.nn.Linear(self.temb_ch,
321
- self.temb_ch),
322
- ])
323
-
324
- # downsampling
325
- self.conv_in = torch.nn.Conv2d(in_channels,
326
- self.ch,
327
- kernel_size=3,
328
- stride=1,
329
- padding=1)
330
-
331
- curr_res = resolution
332
- in_ch_mult = (1,)+tuple(ch_mult)
333
- self.down = nn.ModuleList()
334
- for i_level in range(self.num_resolutions):
335
- block = nn.ModuleList()
336
- attn = nn.ModuleList()
337
- block_in = ch*in_ch_mult[i_level]
338
- block_out = ch*ch_mult[i_level]
339
- for i_block in range(self.num_res_blocks):
340
- block.append(ResnetBlock(in_channels=block_in,
341
- out_channels=block_out,
342
- temb_channels=self.temb_ch,
343
- dropout=dropout))
344
- block_in = block_out
345
- if curr_res in attn_resolutions:
346
- attn.append(make_attn(block_in, attn_type=attn_type))
347
- down = nn.Module()
348
- down.block = block
349
- down.attn = attn
350
- if i_level != self.num_resolutions-1:
351
- down.downsample = Downsample(block_in, resamp_with_conv)
352
- curr_res = curr_res // 2
353
- self.down.append(down)
354
-
355
- # middle
356
- self.mid = nn.Module()
357
- self.mid.block_1 = ResnetBlock(in_channels=block_in,
358
- out_channels=block_in,
359
- temb_channels=self.temb_ch,
360
- dropout=dropout)
361
- self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
362
- self.mid.block_2 = ResnetBlock(in_channels=block_in,
363
- out_channels=block_in,
364
- temb_channels=self.temb_ch,
365
- dropout=dropout)
366
-
367
- # upsampling
368
- self.up = nn.ModuleList()
369
- for i_level in reversed(range(self.num_resolutions)):
370
- block = nn.ModuleList()
371
- attn = nn.ModuleList()
372
- block_out = ch*ch_mult[i_level]
373
- skip_in = ch*ch_mult[i_level]
374
- for i_block in range(self.num_res_blocks+1):
375
- if i_block == self.num_res_blocks:
376
- skip_in = ch*in_ch_mult[i_level]
377
- block.append(ResnetBlock(in_channels=block_in+skip_in,
378
- out_channels=block_out,
379
- temb_channels=self.temb_ch,
380
- dropout=dropout))
381
- block_in = block_out
382
- if curr_res in attn_resolutions:
383
- attn.append(make_attn(block_in, attn_type=attn_type))
384
- up = nn.Module()
385
- up.block = block
386
- up.attn = attn
387
- if i_level != 0:
388
- up.upsample = Upsample(block_in, resamp_with_conv)
389
- curr_res = curr_res * 2
390
- self.up.insert(0, up) # prepend to get consistent order
391
-
392
- # end
393
- self.norm_out = Normalize(block_in)
394
- self.conv_out = torch.nn.Conv2d(block_in,
395
- out_ch,
396
- kernel_size=3,
397
- stride=1,
398
- padding=1)
399
-
400
- def forward(self, x, t=None, context=None):
401
- #assert x.shape[2] == x.shape[3] == self.resolution
402
- if context is not None:
403
- # assume aligned context, cat along channel axis
404
- x = torch.cat((x, context), dim=1)
405
- if self.use_timestep:
406
- # timestep embedding
407
- assert t is not None
408
- temb = get_timestep_embedding(t, self.ch)
409
- temb = self.temb.dense[0](temb)
410
- temb = nonlinearity(temb)
411
- temb = self.temb.dense[1](temb)
412
- else:
413
- temb = None
414
-
415
- # downsampling
416
- hs = [self.conv_in(x)]
417
- for i_level in range(self.num_resolutions):
418
- for i_block in range(self.num_res_blocks):
419
- h = self.down[i_level].block[i_block](hs[-1], temb)
420
- if len(self.down[i_level].attn) > 0:
421
- h = self.down[i_level].attn[i_block](h)
422
- hs.append(h)
423
- if i_level != self.num_resolutions-1:
424
- hs.append(self.down[i_level].downsample(hs[-1]))
425
-
426
- # middle
427
- h = hs[-1]
428
- h = self.mid.block_1(h, temb)
429
- h = self.mid.attn_1(h)
430
- h = self.mid.block_2(h, temb)
431
-
432
- # upsampling
433
- for i_level in reversed(range(self.num_resolutions)):
434
- for i_block in range(self.num_res_blocks+1):
435
- h = self.up[i_level].block[i_block](
436
- torch.cat([h, hs.pop()], dim=1), temb)
437
- if len(self.up[i_level].attn) > 0:
438
- h = self.up[i_level].attn[i_block](h)
439
- if i_level != 0:
440
- h = self.up[i_level].upsample(h)
441
-
442
- # end
443
- h = self.norm_out(h)
444
- h = nonlinearity(h)
445
- h = self.conv_out(h)
446
- return h
447
-
448
- def get_last_layer(self):
449
- return self.conv_out.weight
450
-
451
-
452
- class Encoder(nn.Module):
453
- def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
454
- attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
455
- resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
456
- **ignore_kwargs):
457
- super().__init__()
458
- if use_linear_attn: attn_type = "linear"
459
- self.ch = ch
460
- self.temb_ch = 0
461
- self.num_resolutions = len(ch_mult)
462
- self.num_res_blocks = num_res_blocks
463
- self.resolution = resolution
464
- self.in_channels = in_channels
465
-
466
- # downsampling
467
- self.conv_in = torch.nn.Conv2d(in_channels,
468
- self.ch,
469
- kernel_size=3,
470
- stride=1,
471
- padding=1)
472
-
473
- curr_res = resolution
474
- in_ch_mult = (1,)+tuple(ch_mult)
475
- self.in_ch_mult = in_ch_mult
476
- self.down = nn.ModuleList()
477
- for i_level in range(self.num_resolutions):
478
- block = nn.ModuleList()
479
- attn = nn.ModuleList()
480
- block_in = ch*in_ch_mult[i_level]
481
- block_out = ch*ch_mult[i_level]
482
- for i_block in range(self.num_res_blocks):
483
- block.append(ResnetBlock(in_channels=block_in,
484
- out_channels=block_out,
485
- temb_channels=self.temb_ch,
486
- dropout=dropout))
487
- block_in = block_out
488
- if curr_res in attn_resolutions:
489
- attn.append(make_attn(block_in, attn_type=attn_type))
490
- down = nn.Module()
491
- down.block = block
492
- down.attn = attn
493
- if i_level != self.num_resolutions-1:
494
- down.downsample = Downsample(block_in, resamp_with_conv)
495
- curr_res = curr_res // 2
496
- self.down.append(down)
497
-
498
- # middle
499
- self.mid = nn.Module()
500
- self.mid.block_1 = ResnetBlock(in_channels=block_in,
501
- out_channels=block_in,
502
- temb_channels=self.temb_ch,
503
- dropout=dropout)
504
- self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
505
- self.mid.block_2 = ResnetBlock(in_channels=block_in,
506
- out_channels=block_in,
507
- temb_channels=self.temb_ch,
508
- dropout=dropout)
509
-
510
- # end
511
- self.norm_out = Normalize(block_in)
512
- self.conv_out = torch.nn.Conv2d(block_in,
513
- 2*z_channels if double_z else z_channels,
514
- kernel_size=3,
515
- stride=1,
516
- padding=1)
517
-
518
- def forward(self, x):
519
- # timestep embedding
520
- temb = None
521
-
522
- # downsampling
523
- hs = [self.conv_in(x)]
524
- for i_level in range(self.num_resolutions):
525
- for i_block in range(self.num_res_blocks):
526
- h = self.down[i_level].block[i_block](hs[-1], temb)
527
- if len(self.down[i_level].attn) > 0:
528
- h = self.down[i_level].attn[i_block](h)
529
- hs.append(h)
530
- if i_level != self.num_resolutions-1:
531
- hs.append(self.down[i_level].downsample(hs[-1]))
532
-
533
- # middle
534
- h = hs[-1]
535
- h = self.mid.block_1(h, temb)
536
- h = self.mid.attn_1(h)
537
- h = self.mid.block_2(h, temb)
538
-
539
- # end
540
- h = self.norm_out(h)
541
- h = nonlinearity(h)
542
- h = self.conv_out(h)
543
- return h
544
-
545
-
546
- class Decoder(nn.Module):
547
- def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
548
- attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
549
- resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
550
- attn_type="vanilla", **ignorekwargs):
551
- super().__init__()
552
- if use_linear_attn: attn_type = "linear"
553
- self.ch = ch
554
- self.temb_ch = 0
555
- self.num_resolutions = len(ch_mult)
556
- self.num_res_blocks = num_res_blocks
557
- self.resolution = resolution
558
- self.in_channels = in_channels
559
- self.give_pre_end = give_pre_end
560
- self.tanh_out = tanh_out
561
-
562
- # compute in_ch_mult, block_in and curr_res at lowest res
563
- in_ch_mult = (1,)+tuple(ch_mult)
564
- block_in = ch*ch_mult[self.num_resolutions-1]
565
- curr_res = resolution // 2**(self.num_resolutions-1)
566
- self.z_shape = (1,z_channels,curr_res,curr_res)
567
- print("Working with z of shape {} = {} dimensions.".format(
568
- self.z_shape, np.prod(self.z_shape)))
569
-
570
- # z to block_in
571
- self.conv_in = torch.nn.Conv2d(z_channels,
572
- block_in,
573
- kernel_size=3,
574
- stride=1,
575
- padding=1)
576
-
577
- # middle
578
- self.mid = nn.Module()
579
- self.mid.block_1 = ResnetBlock(in_channels=block_in,
580
- out_channels=block_in,
581
- temb_channels=self.temb_ch,
582
- dropout=dropout)
583
- self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
584
- self.mid.block_2 = ResnetBlock(in_channels=block_in,
585
- out_channels=block_in,
586
- temb_channels=self.temb_ch,
587
- dropout=dropout)
588
-
589
- # upsampling
590
- self.up = nn.ModuleList()
591
- for i_level in reversed(range(self.num_resolutions)):
592
- block = nn.ModuleList()
593
- attn = nn.ModuleList()
594
- block_out = ch*ch_mult[i_level]
595
- for i_block in range(self.num_res_blocks+1):
596
- block.append(ResnetBlock(in_channels=block_in,
597
- out_channels=block_out,
598
- temb_channels=self.temb_ch,
599
- dropout=dropout))
600
- block_in = block_out
601
- if curr_res in attn_resolutions:
602
- attn.append(make_attn(block_in, attn_type=attn_type))
603
- up = nn.Module()
604
- up.block = block
605
- up.attn = attn
606
- if i_level != 0:
607
- up.upsample = Upsample(block_in, resamp_with_conv)
608
- curr_res = curr_res * 2
609
- self.up.insert(0, up) # prepend to get consistent order
610
-
611
- # end
612
- self.norm_out = Normalize(block_in)
613
- self.conv_out = torch.nn.Conv2d(block_in,
614
- out_ch,
615
- kernel_size=3,
616
- stride=1,
617
- padding=1)
618
-
619
- def forward(self, z):
620
- #assert z.shape[1:] == self.z_shape[1:]
621
- self.last_z_shape = z.shape
622
-
623
- # timestep embedding
624
- temb = None
625
-
626
- # z to block_in
627
- h = self.conv_in(z)
628
-
629
- # middle
630
- h = self.mid.block_1(h, temb)
631
- h = self.mid.attn_1(h)
632
- h = self.mid.block_2(h, temb)
633
-
634
- # upsampling
635
- for i_level in reversed(range(self.num_resolutions)):
636
- for i_block in range(self.num_res_blocks+1):
637
- h = self.up[i_level].block[i_block](h, temb)
638
- if len(self.up[i_level].attn) > 0:
639
- h = self.up[i_level].attn[i_block](h)
640
- if i_level != 0:
641
- h = self.up[i_level].upsample(h)
642
-
643
- # end
644
- if self.give_pre_end:
645
- return h
646
-
647
- h = self.norm_out(h)
648
- h = nonlinearity(h)
649
- h = self.conv_out(h)
650
- if self.tanh_out:
651
- h = torch.tanh(h)
652
- return h
653
-
654
-
655
- class SimpleDecoder(nn.Module):
656
- def __init__(self, in_channels, out_channels, *args, **kwargs):
657
- super().__init__()
658
- self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
659
- ResnetBlock(in_channels=in_channels,
660
- out_channels=2 * in_channels,
661
- temb_channels=0, dropout=0.0),
662
- ResnetBlock(in_channels=2 * in_channels,
663
- out_channels=4 * in_channels,
664
- temb_channels=0, dropout=0.0),
665
- ResnetBlock(in_channels=4 * in_channels,
666
- out_channels=2 * in_channels,
667
- temb_channels=0, dropout=0.0),
668
- nn.Conv2d(2*in_channels, in_channels, 1),
669
- Upsample(in_channels, with_conv=True)])
670
- # end
671
- self.norm_out = Normalize(in_channels)
672
- self.conv_out = torch.nn.Conv2d(in_channels,
673
- out_channels,
674
- kernel_size=3,
675
- stride=1,
676
- padding=1)
677
-
678
- def forward(self, x):
679
- for i, layer in enumerate(self.model):
680
- if i in [1,2,3]:
681
- x = layer(x, None)
682
- else:
683
- x = layer(x)
684
-
685
- h = self.norm_out(x)
686
- h = nonlinearity(h)
687
- x = self.conv_out(h)
688
- return x
689
-
690
-
691
- class UpsampleDecoder(nn.Module):
692
- def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
693
- ch_mult=(2,2), dropout=0.0):
694
- super().__init__()
695
- # upsampling
696
- self.temb_ch = 0
697
- self.num_resolutions = len(ch_mult)
698
- self.num_res_blocks = num_res_blocks
699
- block_in = in_channels
700
- curr_res = resolution // 2 ** (self.num_resolutions - 1)
701
- self.res_blocks = nn.ModuleList()
702
- self.upsample_blocks = nn.ModuleList()
703
- for i_level in range(self.num_resolutions):
704
- res_block = []
705
- block_out = ch * ch_mult[i_level]
706
- for i_block in range(self.num_res_blocks + 1):
707
- res_block.append(ResnetBlock(in_channels=block_in,
708
- out_channels=block_out,
709
- temb_channels=self.temb_ch,
710
- dropout=dropout))
711
- block_in = block_out
712
- self.res_blocks.append(nn.ModuleList(res_block))
713
- if i_level != self.num_resolutions - 1:
714
- self.upsample_blocks.append(Upsample(block_in, True))
715
- curr_res = curr_res * 2
716
-
717
- # end
718
- self.norm_out = Normalize(block_in)
719
- self.conv_out = torch.nn.Conv2d(block_in,
720
- out_channels,
721
- kernel_size=3,
722
- stride=1,
723
- padding=1)
724
-
725
- def forward(self, x):
726
- # upsampling
727
- h = x
728
- for k, i_level in enumerate(range(self.num_resolutions)):
729
- for i_block in range(self.num_res_blocks + 1):
730
- h = self.res_blocks[i_level][i_block](h, None)
731
- if i_level != self.num_resolutions - 1:
732
- h = self.upsample_blocks[k](h)
733
- h = self.norm_out(h)
734
- h = nonlinearity(h)
735
- h = self.conv_out(h)
736
- return h
737
-
738
-
739
- class LatentRescaler(nn.Module):
740
- def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
741
- super().__init__()
742
- # residual block, interpolate, residual block
743
- self.factor = factor
744
- self.conv_in = nn.Conv2d(in_channels,
745
- mid_channels,
746
- kernel_size=3,
747
- stride=1,
748
- padding=1)
749
- self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
750
- out_channels=mid_channels,
751
- temb_channels=0,
752
- dropout=0.0) for _ in range(depth)])
753
- self.attn = AttnBlock(mid_channels)
754
- self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
755
- out_channels=mid_channels,
756
- temb_channels=0,
757
- dropout=0.0) for _ in range(depth)])
758
-
759
- self.conv_out = nn.Conv2d(mid_channels,
760
- out_channels,
761
- kernel_size=1,
762
- )
763
-
764
- def forward(self, x):
765
- x = self.conv_in(x)
766
- for block in self.res_block1:
767
- x = block(x, None)
768
- x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
769
- x = self.attn(x)
770
- for block in self.res_block2:
771
- x = block(x, None)
772
- x = self.conv_out(x)
773
- return x
774
-
775
-
776
- class MergedRescaleEncoder(nn.Module):
777
- def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
778
- attn_resolutions, dropout=0.0, resamp_with_conv=True,
779
- ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
780
- super().__init__()
781
- intermediate_chn = ch * ch_mult[-1]
782
- self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
783
- z_channels=intermediate_chn, double_z=False, resolution=resolution,
784
- attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
785
- out_ch=None)
786
- self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
787
- mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
788
-
789
- def forward(self, x):
790
- x = self.encoder(x)
791
- x = self.rescaler(x)
792
- return x
793
-
794
-
795
- class MergedRescaleDecoder(nn.Module):
796
- def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
797
- dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
798
- super().__init__()
799
- tmp_chn = z_channels*ch_mult[-1]
800
- self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
801
- resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
802
- ch_mult=ch_mult, resolution=resolution, ch=ch)
803
- self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
804
- out_channels=tmp_chn, depth=rescale_module_depth)
805
-
806
- def forward(self, x):
807
- x = self.rescaler(x)
808
- x = self.decoder(x)
809
- return x
810
-
811
-
812
- class Upsampler(nn.Module):
813
- def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
814
- super().__init__()
815
- assert out_size >= in_size
816
- num_blocks = int(np.log2(out_size//in_size))+1
817
- factor_up = 1.+ (out_size % in_size)
818
- print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
819
- self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
820
- out_channels=in_channels)
821
- self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
822
- attn_resolutions=[], in_channels=None, ch=in_channels,
823
- ch_mult=[ch_mult for _ in range(num_blocks)])
824
-
825
- def forward(self, x):
826
- x = self.rescaler(x)
827
- x = self.decoder(x)
828
- return x
829
-
830
-
831
- class Resize(nn.Module):
832
- def __init__(self, in_channels=None, learned=False, mode="bilinear"):
833
- super().__init__()
834
- self.with_conv = learned
835
- self.mode = mode
836
- if self.with_conv:
837
- print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
838
- raise NotImplementedError()
839
- assert in_channels is not None
840
- # no asymmetric padding in torch conv, must do it ourselves
841
- self.conv = torch.nn.Conv2d(in_channels,
842
- in_channels,
843
- kernel_size=4,
844
- stride=2,
845
- padding=1)
846
-
847
- def forward(self, x, scale_factor=1.0):
848
- if scale_factor==1.0:
849
- return x
850
- else:
851
- x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
852
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/modules/diffusionmodules/openaimodel.py DELETED
@@ -1,853 +0,0 @@
1
- from abc import abstractmethod
2
- import math
3
-
4
- import numpy as np
5
- import torch as th
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
-
9
- from ldm.modules.diffusionmodules.util import (
10
- checkpoint,
11
- conv_nd,
12
- linear,
13
- avg_pool_nd,
14
- zero_module,
15
- normalization,
16
- timestep_embedding,
17
- )
18
- from ldm.modules.attention import SpatialTransformer#
19
- from ldm.modules.attention_dcn_control import SpatialTransformer_dcn
20
- from ldm.util import exists
21
-
22
-
23
- # dummy replace
24
- def convert_module_to_f16(x):
25
- pass
26
-
27
- def convert_module_to_f32(x):
28
- pass
29
-
30
-
31
- ## go
32
- class AttentionPool2d(nn.Module):
33
- """
34
- Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
35
- """
36
-
37
- def __init__(
38
- self,
39
- spacial_dim: int,
40
- embed_dim: int,
41
- num_heads_channels: int,
42
- output_dim: int = None,
43
- ):
44
- super().__init__()
45
- self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5)
46
- self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
47
- self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
48
- self.num_heads = embed_dim // num_heads_channels
49
- self.attention = QKVAttention(self.num_heads)
50
-
51
- def forward(self, x):
52
- b, c, *_spatial = x.shape
53
- x = x.reshape(b, c, -1) # NC(HW)
54
- x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
55
- x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
56
- x = self.qkv_proj(x)
57
- x = self.attention(x)
58
- x = self.c_proj(x)
59
- return x[:, :, 0]
60
-
61
-
62
- class TimestepBlock(nn.Module):
63
- """
64
- Any module where forward() takes timestep embeddings as a second argument.
65
- """
66
-
67
- @abstractmethod
68
- def forward(self, x, emb):
69
- """
70
- Apply the module to `x` given `emb` timestep embeddings.
71
- """
72
-
73
-
74
- class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
75
- """
76
- A sequential module that passes timestep embeddings to the children that
77
- support it as an extra input.
78
- """
79
-
80
- def forward(self, x, emb, context=None):#,timestep=None,dcn_guide=None):
81
- for layer in self:
82
- if isinstance(layer, TimestepBlock):
83
- x = layer(x, emb)
84
- elif isinstance(layer, SpatialTransformer):
85
- x = layer(x, context=context)#,timestep=timestep)
86
- elif isinstance(layer, SpatialTransformer_dcn):
87
- # x = layer(x, context,dcn_guide)
88
- x = layer(x, context)
89
- else:
90
- x = layer(x)
91
- return x
92
-
93
-
94
- class Upsample(nn.Module):
95
- """
96
- An upsampling layer with an optional convolution.
97
- :param channels: channels in the inputs and outputs.
98
- :param use_conv: a bool determining if a convolution is applied.
99
- :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
100
- upsampling occurs in the inner-two dimensions.
101
- """
102
-
103
- def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
104
- super().__init__()
105
- self.channels = channels
106
- self.out_channels = out_channels or channels
107
- self.use_conv = use_conv
108
- self.dims = dims
109
- if use_conv:
110
- self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)
111
-
112
- def forward(self, x):
113
- assert x.shape[1] == self.channels
114
- if self.dims == 3:
115
- x = F.interpolate(
116
- x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
117
- )
118
- else:
119
- x = F.interpolate(x, scale_factor=2, mode="nearest")
120
- if self.use_conv:
121
- x = self.conv(x)
122
- return x
123
-
124
- class TransposedUpsample(nn.Module):
125
- 'Learned 2x upsampling without padding'
126
- def __init__(self, channels, out_channels=None, ks=5):
127
- super().__init__()
128
- self.channels = channels
129
- self.out_channels = out_channels or channels
130
-
131
- self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2)
132
-
133
- def forward(self,x):
134
- return self.up(x)
135
-
136
-
137
- class Downsample(nn.Module):
138
- """
139
- A downsampling layer with an optional convolution.
140
- :param channels: channels in the inputs and outputs.
141
- :param use_conv: a bool determining if a convolution is applied.
142
- :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
143
- downsampling occurs in the inner-two dimensions.
144
- """
145
-
146
- def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1):
147
- super().__init__()
148
- self.channels = channels
149
- self.out_channels = out_channels or channels
150
- self.use_conv = use_conv
151
- self.dims = dims
152
- stride = 2 if dims != 3 else (1, 2, 2)
153
- if use_conv:
154
- self.op = conv_nd(
155
- dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
156
- )
157
- else:
158
- assert self.channels == self.out_channels
159
- self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
160
-
161
- def forward(self, x):
162
- assert x.shape[1] == self.channels
163
- return self.op(x)
164
-
165
-
166
- class ResBlock(TimestepBlock):
167
- """
168
- A residual block that can optionally change the number of channels.
169
- :param channels: the number of input channels.
170
- :param emb_channels: the number of timestep embedding channels.
171
- :param dropout: the rate of dropout.
172
- :param out_channels: if specified, the number of out channels.
173
- :param use_conv: if True and out_channels is specified, use a spatial
174
- convolution instead of a smaller 1x1 convolution to change the
175
- channels in the skip connection.
176
- :param dims: determines if the signal is 1D, 2D, or 3D.
177
- :param use_checkpoint: if True, use gradient checkpointing on this module.
178
- :param up: if True, use this block for upsampling.
179
- :param down: if True, use this block for downsampling.
180
- """
181
-
182
- def __init__(
183
- self,
184
- channels,
185
- emb_channels,
186
- dropout,
187
- out_channels=None,
188
- use_conv=False,
189
- use_scale_shift_norm=False,
190
- dims=2,
191
- use_checkpoint=False,
192
- up=False,
193
- down=False,
194
- ):
195
- super().__init__()
196
- self.channels = channels
197
- self.emb_channels = emb_channels
198
- self.dropout = dropout
199
- self.out_channels = out_channels or channels
200
- self.use_conv = use_conv
201
- self.use_checkpoint = use_checkpoint
202
- self.use_scale_shift_norm = use_scale_shift_norm
203
-
204
- self.in_layers = nn.Sequential(
205
- normalization(channels),
206
- nn.SiLU(),
207
- conv_nd(dims, channels, self.out_channels, 3, padding=1),
208
- )
209
-
210
- self.updown = up or down
211
-
212
- if up:
213
- self.h_upd = Upsample(channels, False, dims)
214
- self.x_upd = Upsample(channels, False, dims)
215
- elif down:
216
- self.h_upd = Downsample(channels, False, dims)
217
- self.x_upd = Downsample(channels, False, dims)
218
- else:
219
- self.h_upd = self.x_upd = nn.Identity()
220
-
221
- self.emb_layers = nn.Sequential(
222
- nn.SiLU(),
223
- linear(
224
- emb_channels,
225
- 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
226
- ),
227
- )
228
- self.out_layers = nn.Sequential(
229
- normalization(self.out_channels),
230
- nn.SiLU(),
231
- nn.Dropout(p=dropout),
232
- zero_module(
233
- conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
234
- ),
235
- )
236
-
237
- if self.out_channels == channels:
238
- self.skip_connection = nn.Identity()
239
- elif use_conv:
240
- self.skip_connection = conv_nd(
241
- dims, channels, self.out_channels, 3, padding=1
242
- )
243
- else:
244
- self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
245
-
246
- def forward(self, x, emb):
247
- """
248
- Apply the block to a Tensor, conditioned on a timestep embedding.
249
- :param x: an [N x C x ...] Tensor of features.
250
- :param emb: an [N x emb_channels] Tensor of timestep embeddings.
251
- :return: an [N x C x ...] Tensor of outputs.
252
- """
253
- return checkpoint(
254
- self._forward, (x, emb), self.parameters(), self.use_checkpoint
255
- )
256
-
257
-
258
- def _forward(self, x, emb):
259
- if self.updown:
260
- in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
261
- h = in_rest(x)
262
- h = self.h_upd(h)
263
- x = self.x_upd(x)
264
- h = in_conv(h)
265
- else:
266
- h = self.in_layers(x)
267
- emb_out = self.emb_layers(emb).type(h.dtype)
268
- while len(emb_out.shape) < len(h.shape):
269
- emb_out = emb_out[..., None]
270
- if self.use_scale_shift_norm:
271
- out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
272
- scale, shift = th.chunk(emb_out, 2, dim=1)
273
- h = out_norm(h) * (1 + scale) + shift
274
- h = out_rest(h)
275
- else:
276
- h = h + emb_out
277
- h = self.out_layers(h)
278
- return self.skip_connection(x) + h
279
-
280
-
281
- class AttentionBlock(nn.Module):
282
- """
283
- An attention block that allows spatial positions to attend to each other.
284
- Originally ported from here, but adapted to the N-d case.
285
- https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
286
- """
287
-
288
- def __init__(
289
- self,
290
- channels,
291
- num_heads=1,
292
- num_head_channels=-1,
293
- use_checkpoint=False,
294
- use_new_attention_order=False,
295
- ):
296
- super().__init__()
297
- self.channels = channels
298
- if num_head_channels == -1:
299
- self.num_heads = num_heads
300
- else:
301
- assert (
302
- channels % num_head_channels == 0
303
- ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
304
- self.num_heads = channels // num_head_channels
305
- self.use_checkpoint = use_checkpoint
306
- self.norm = normalization(channels)
307
- self.qkv = conv_nd(1, channels, channels * 3, 1)
308
- if use_new_attention_order:
309
- # split qkv before split heads
310
- self.attention = QKVAttention(self.num_heads)
311
- else:
312
- # split heads before split qkv
313
- self.attention = QKVAttentionLegacy(self.num_heads)
314
-
315
- self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
316
- # self.cnnhead = CnnHead(512,num_classes=32,window_size=channels)
317
- def forward(self, x):
318
- return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
319
- #return pt_checkpoint(self._forward, x) # pytorch
320
-
321
- def _forward(self, x):
322
- b, c, *spatial = x.shape
323
- x = x.reshape(b, c, -1)
324
- qkv = self.qkv(self.norm(x))
325
- h = self.attention(qkv)
326
- h = self.proj_out(h)
327
- # h = self.cnnhead(h)
328
- return (x + h).reshape(b, c, *spatial)
329
-
330
-
331
- def count_flops_attn(model, _x, y):
332
- """
333
- A counter for the `thop` package to count the operations in an
334
- attention operation.
335
- Meant to be used like:
336
- macs, params = thop.profile(
337
- model,
338
- inputs=(inputs, timestamps),
339
- custom_ops={QKVAttention: QKVAttention.count_flops},
340
- )
341
- """
342
- b, c, *spatial = y[0].shape
343
- num_spatial = int(np.prod(spatial))
344
- # We perform two matmuls with the same number of ops.
345
- # The first computes the weight matrix, the second computes
346
- # the combination of the value vectors.
347
- matmul_ops = 2 * b * (num_spatial ** 2) * c
348
- model.total_ops += th.DoubleTensor([matmul_ops])
349
-
350
-
351
- class QKVAttentionLegacy(nn.Module):
352
- """
353
- A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
354
- """
355
-
356
- def __init__(self, n_heads):
357
- super().__init__()
358
- self.n_heads = n_heads
359
-
360
- def forward(self, qkv):
361
- """
362
- Apply QKV attention.
363
- :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
364
- :return: an [N x (H * C) x T] tensor after attention.
365
- """
366
- bs, width, length = qkv.shape
367
- assert width % (3 * self.n_heads) == 0
368
- ch = width // (3 * self.n_heads)
369
- q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
370
- scale = 1 / math.sqrt(math.sqrt(ch))
371
- weight = th.einsum(
372
- "bct,bcs->bts", q * scale, k * scale
373
- ) # More stable with f16 than dividing afterwards
374
- weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
375
- a = th.einsum("bts,bcs->bct", weight, v)
376
- return a.reshape(bs, -1, length)
377
-
378
- @staticmethod
379
- def count_flops(model, _x, y):
380
- return count_flops_attn(model, _x, y)
381
-
382
-
383
- class QKVAttention(nn.Module):
384
- """
385
- A module which performs QKV attention and splits in a different order.
386
- """
387
-
388
- def __init__(self, n_heads):
389
- super().__init__()
390
- self.n_heads = n_heads
391
-
392
- def forward(self, qkv):
393
- """
394
- Apply QKV attention.
395
- :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
396
- :return: an [N x (H * C) x T] tensor after attention.
397
- """
398
- bs, width, length = qkv.shape
399
- assert width % (3 * self.n_heads) == 0
400
- ch = width // (3 * self.n_heads)
401
- q, k, v = qkv.chunk(3, dim=1)
402
- scale = 1 / math.sqrt(math.sqrt(ch))
403
- weight = th.einsum(
404
- "bct,bcs->bts",
405
- (q * scale).view(bs * self.n_heads, ch, length),
406
- (k * scale).view(bs * self.n_heads, ch, length),
407
- ) # More stable with f16 than dividing afterwards
408
- weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
409
- a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
410
- return a.reshape(bs, -1, length)
411
-
412
- @staticmethod
413
- def count_flops(model, _x, y):
414
- return count_flops_attn(model, _x, y)
415
-
416
- # class ModulatedDeformConv(nn.Module):
417
- # """A ModulatedDeformable Conv Encapsulation that acts as normal Conv layers.
418
-
419
- # Args:
420
- # in_channels (int): Same as nn.Conv2d.
421
- # out_channels (int): Same as nn.Conv2d.
422
- # kernel_size (int or tuple[int]): Same as nn.Conv2d.
423
- # stride (int or tuple[int]): Same as nn.Conv2d.
424
- # padding (int or tuple[int]): Same as nn.Conv2d.
425
- # dilation (int or tuple[int]): Same as nn.Conv2d.
426
- # groups (int): Same as nn.Conv2d.
427
- # bias (bool or str): If specified as `auto`, it will be decided by the
428
- # norm_cfg. Bias will be set as True if norm_cfg is None, otherwise
429
- # False.
430
- # """
431
-
432
- # _version = 2
433
-
434
- # def __init__(self, *args, **kwargs):
435
- # super(ModulatedDeformConv, self).__init__(*args, **kwargs)
436
-
437
- # self.conv_offset = nn.Conv2d(
438
- # self.in_channels,
439
- # self.deformable_groups * 3 * self.kernel_size[0] * self.kernel_size[1],
440
- # kernel_size=self.kernel_size,
441
- # stride=_pair(self.stride),
442
- # padding=_pair(self.padding),
443
- # dilation=_pair(self.dilation),
444
- # bias=True)
445
- # self.init_weights()
446
-
447
- # def init_weights(self):
448
- # super(ModulatedDeformConv, self).init_weights()
449
- # if hasattr(self, 'conv_offset'):
450
- # self.conv_offset.weight.data.zero_()
451
- # self.conv_offset.bias.data.zero_()
452
-
453
- # def forward(self, x):
454
- # out = self.conv_offset(x)
455
- # o1, o2, mask = th.chunk(out, 3, dim=1)
456
- # offset = th.cat((o1, o2), dim=1)
457
- # mask = th.sigmoid(mask)
458
- # return nn.deform_conv2d(x, offset, self.weight, self.bias, self.stride, self.padding, self.dilation,mask,
459
- # self.groups, self.deformable_groups)
460
-
461
- from einops import rearrange
462
- class CnnHead(nn.Module):
463
- def __init__(self, embed_dim, num_classes, window_size):
464
- super().__init__()
465
- self.embed_dim = embed_dim
466
- self.num_classes = num_classes
467
- self.window_size = window_size
468
-
469
- self.cnnhead = nn.Conv2d(embed_dim, num_classes, kernel_size=3, stride=1, padding=1, padding_mode='reflect')
470
-
471
- def forward(self, x):
472
- x = rearrange(x, 'b (p1 p2) c -> b c p1 p2', p1=self.window_size, p2=self.window_size)
473
- x = self.cnnhead(x)
474
- x = rearrange(x, 'b c p1 p2 -> b (p1 p2) c')
475
- return x
476
-
477
- class UNetModel(nn.Module):
478
- """
479
- The full UNet model with attention and timestep embedding.
480
- :param in_channels: channels in the input Tensor.
481
- :param model_channels: base channel count for the model.
482
- :param out_channels: channels in the output Tensor.
483
- :param num_res_blocks: number of residual blocks per downsample.
484
- :param attention_resolutions: a collection of downsample rates at which
485
- attention will take place. May be a set, list, or tuple.
486
- For example, if this contains 4, then at 4x downsampling, attention
487
- will be used.
488
- :param dropout: the dropout probability.
489
- :param channel_mult: channel multiplier for each level of the UNet.
490
- :param conv_resample: if True, use learned convolutions for upsampling and
491
- downsampling.
492
- :param dims: determines if the signal is 1D, 2D, or 3D.
493
- :param num_classes: if specified (as an int), then this model will be
494
- class-conditional with `num_classes` classes.
495
- :param use_checkpoint: use gradient checkpointing to reduce memory usage.
496
- :param num_heads: the number of attention heads in each attention layer.
497
- :param num_heads_channels: if specified, ignore num_heads and instead use
498
- a fixed channel width per attention head.
499
- :param num_heads_upsample: works with num_heads to set a different number
500
- of heads for upsampling. Deprecated.
501
- :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
502
- :param resblock_updown: use residual blocks for up/downsampling.
503
- :param use_new_attention_order: use a different attention pattern for potentially
504
- increased efficiency.
505
- """
506
-
507
- def __init__(
508
- self,
509
- image_size,
510
- in_channels,
511
- model_channels,
512
- out_channels,
513
- num_res_blocks,
514
- attention_resolutions,
515
- dropout=0,
516
- channel_mult=(1, 2, 4, 8),
517
- conv_resample=True,
518
- dims=2,
519
- num_classes=None,
520
- use_checkpoint=False,
521
- use_fp16=False,
522
- num_heads=-1,
523
- num_head_channels=-1,
524
- num_heads_upsample=-1,
525
- use_scale_shift_norm=False,
526
- resblock_updown=False,
527
- use_new_attention_order=False,
528
- use_spatial_transformer=False, # custom transformer support
529
- transformer_depth=1, # custom transformer support
530
- context_dim=None, # custom transformer support
531
- n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
532
- legacy=True,
533
- disable_self_attentions=None,
534
- num_attention_blocks=None,
535
- disable_middle_self_attn=False,
536
- use_linear_in_transformer=False,
537
- ):
538
- super().__init__()
539
- if use_spatial_transformer:
540
- assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
541
-
542
- if context_dim is not None:
543
- assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
544
- from omegaconf.listconfig import ListConfig
545
- if type(context_dim) == ListConfig:
546
- context_dim = list(context_dim)
547
-
548
- if num_heads_upsample == -1:
549
- num_heads_upsample = num_heads
550
-
551
- if num_heads == -1:
552
- assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
553
-
554
- if num_head_channels == -1:
555
- assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
556
-
557
- self.image_size = image_size
558
- self.in_channels = in_channels
559
- self.model_channels = model_channels
560
- self.out_channels = out_channels
561
- if isinstance(num_res_blocks, int):
562
- self.num_res_blocks = len(channel_mult) * [num_res_blocks]
563
- else:
564
- if len(num_res_blocks) != len(channel_mult):
565
- raise ValueError("provide num_res_blocks either as an int (globally constant) or "
566
- "as a list/tuple (per-level) with the same length as channel_mult")
567
- self.num_res_blocks = num_res_blocks
568
- if disable_self_attentions is not None:
569
- # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
570
- assert len(disable_self_attentions) == len(channel_mult)
571
- if num_attention_blocks is not None:
572
- assert len(num_attention_blocks) == len(self.num_res_blocks)
573
- assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
574
- print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
575
- f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
576
- f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
577
- f"attention will still not be set.")
578
-
579
- self.attention_resolutions = attention_resolutions
580
- self.dropout = dropout
581
- self.channel_mult = channel_mult
582
- self.conv_resample = conv_resample
583
- self.num_classes = num_classes
584
- self.use_checkpoint = use_checkpoint
585
- self.dtype = th.float16 if use_fp16 else th.float32
586
- self.num_heads = num_heads
587
- self.num_head_channels = num_head_channels
588
- self.num_heads_upsample = num_heads_upsample
589
- self.predict_codebook_ids = n_embed is not None
590
-
591
- time_embed_dim = model_channels * 4
592
- self.time_embed = nn.Sequential(
593
- linear(model_channels, time_embed_dim),
594
- nn.SiLU(),
595
- linear(time_embed_dim, time_embed_dim),
596
- )
597
-
598
- if self.num_classes is not None:
599
- if isinstance(self.num_classes, int):
600
- self.label_emb = nn.Embedding(num_classes, time_embed_dim)
601
- elif self.num_classes == "continuous":
602
- print("setting up linear c_adm embedding layer")
603
- self.label_emb = nn.Linear(1, time_embed_dim)
604
- else:
605
- raise ValueError()
606
-
607
- self.input_blocks = nn.ModuleList(
608
- [
609
- TimestepEmbedSequential(
610
- conv_nd(dims, in_channels, model_channels, 3, padding=1)
611
- )
612
- ]
613
- )
614
- self._feature_size = model_channels
615
- input_block_chans = [model_channels]
616
- ch = model_channels
617
- ds = 1
618
- for level, mult in enumerate(channel_mult):
619
- for nr in range(self.num_res_blocks[level]):
620
- layers = [
621
- ResBlock(
622
- ch,
623
- time_embed_dim,
624
- dropout,
625
- out_channels=mult * model_channels,
626
- dims=dims,
627
- use_checkpoint=use_checkpoint,
628
- use_scale_shift_norm=use_scale_shift_norm,
629
- )
630
- ]
631
- ch = mult * model_channels
632
- if ds in attention_resolutions:
633
- if num_head_channels == -1:
634
- dim_head = ch // num_heads
635
- else:
636
- num_heads = ch // num_head_channels
637
- dim_head = num_head_channels
638
- if legacy:
639
- #num_heads = 1
640
- dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
641
- if exists(disable_self_attentions):
642
- disabled_sa = disable_self_attentions[level]
643
- else:
644
- disabled_sa = False
645
-
646
- if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
647
- layers.append(
648
- AttentionBlock(
649
- ch,
650
- use_checkpoint=use_checkpoint,
651
- num_heads=num_heads,
652
- num_head_channels=dim_head,
653
- use_new_attention_order=use_new_attention_order,
654
- ) if not use_spatial_transformer else SpatialTransformer(
655
- ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
656
- disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
657
- use_checkpoint=use_checkpoint
658
- )
659
- )
660
- self.input_blocks.append(TimestepEmbedSequential(*layers))
661
- self._feature_size += ch
662
- input_block_chans.append(ch)
663
- if level != len(channel_mult) - 1:
664
- out_ch = ch
665
- self.input_blocks.append(
666
- TimestepEmbedSequential(
667
- ResBlock(
668
- ch,
669
- time_embed_dim,
670
- dropout,
671
- out_channels=out_ch,
672
- dims=dims,
673
- use_checkpoint=use_checkpoint,
674
- use_scale_shift_norm=use_scale_shift_norm,
675
- down=True,
676
- )
677
- if resblock_updown
678
- else Downsample(
679
- ch, conv_resample, dims=dims, out_channels=out_ch
680
- )
681
- )
682
- )
683
- ch = out_ch
684
- input_block_chans.append(ch)
685
- ds *= 2
686
- self._feature_size += ch
687
-
688
- if num_head_channels == -1:
689
- dim_head = ch // num_heads
690
- else:
691
- num_heads = ch // num_head_channels
692
- dim_head = num_head_channels
693
- if legacy:
694
- #num_heads = 1
695
- dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
696
- self.middle_block = TimestepEmbedSequential(
697
- ResBlock(
698
- ch,
699
- time_embed_dim,
700
- dropout,
701
- dims=dims,
702
- use_checkpoint=use_checkpoint,
703
- use_scale_shift_norm=use_scale_shift_norm,
704
- ),
705
- AttentionBlock(
706
- ch,
707
- use_checkpoint=use_checkpoint,
708
- num_heads=num_heads,
709
- num_head_channels=dim_head,
710
- use_new_attention_order=use_new_attention_order,
711
- ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
712
- ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
713
- disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
714
- use_checkpoint=use_checkpoint
715
- ),
716
- ResBlock(
717
- ch,
718
- time_embed_dim,
719
- dropout,
720
- dims=dims,
721
- use_checkpoint=use_checkpoint,
722
- use_scale_shift_norm=use_scale_shift_norm,
723
- ),
724
- )
725
- self._feature_size += ch
726
-
727
- self.output_blocks = nn.ModuleList([])
728
- for level, mult in list(enumerate(channel_mult))[::-1]:
729
- for i in range(self.num_res_blocks[level] + 1):
730
- ich = input_block_chans.pop()
731
- layers = [
732
- ResBlock(
733
- ch + ich,
734
- time_embed_dim,
735
- dropout,
736
- out_channels=model_channels * mult,
737
- dims=dims,
738
- use_checkpoint=use_checkpoint,
739
- use_scale_shift_norm=use_scale_shift_norm,
740
- )
741
- ]
742
- ch = model_channels * mult
743
- if ds in attention_resolutions:
744
- if num_head_channels == -1:
745
- dim_head = ch // num_heads
746
- else:
747
- num_heads = ch // num_head_channels
748
- dim_head = num_head_channels
749
- if legacy:
750
- #num_heads = 1
751
- dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
752
- if exists(disable_self_attentions):
753
- disabled_sa = disable_self_attentions[level]
754
- else:
755
- disabled_sa = False
756
-
757
- if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
758
- layers.append(
759
- AttentionBlock(
760
- ch,
761
- use_checkpoint=use_checkpoint,
762
- num_heads=num_heads_upsample,
763
- num_head_channels=dim_head,
764
- use_new_attention_order=use_new_attention_order,
765
- ) if not use_spatial_transformer else SpatialTransformer(
766
- ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
767
- disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
768
- use_checkpoint=use_checkpoint
769
- )
770
- )
771
- # layers.append(CnnHead(ch, ch, window_size=ch // 8))
772
- if level and i == self.num_res_blocks[level]:
773
- out_ch = ch
774
- layers.append(
775
- ResBlock(
776
- ch,
777
- time_embed_dim,
778
- dropout,
779
- out_channels=out_ch,
780
- dims=dims,
781
- use_checkpoint=use_checkpoint,
782
- use_scale_shift_norm=use_scale_shift_norm,
783
- up=True,
784
- )
785
- if resblock_updown
786
- else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
787
- )
788
- # layers.append(CnnHead(ch, ch, window_size=ch // 8))
789
- ds //= 2
790
- self.output_blocks.append(TimestepEmbedSequential(*layers))
791
- self._feature_size += ch
792
-
793
- self.out = nn.Sequential(
794
- normalization(ch),
795
- nn.SiLU(),
796
- zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
797
- )
798
- if self.predict_codebook_ids:
799
- self.id_predictor = nn.Sequential(
800
- normalization(ch),
801
- conv_nd(dims, model_channels, n_embed, 1),
802
- #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
803
- )
804
-
805
- def convert_to_fp16(self):
806
- """
807
- Convert the torso of the model to float16.
808
- """
809
- self.input_blocks.apply(convert_module_to_f16)
810
- self.middle_block.apply(convert_module_to_f16)
811
- self.output_blocks.apply(convert_module_to_f16)
812
-
813
- def convert_to_fp32(self):
814
- """
815
- Convert the torso of the model to float32.
816
- """
817
- self.input_blocks.apply(convert_module_to_f32)
818
- self.middle_block.apply(convert_module_to_f32)
819
- self.output_blocks.apply(convert_module_to_f32)
820
-
821
- def forward(self, x, timesteps=None, context=None, y=None,**kwargs):
822
- """
823
- Apply the model to an input batch.
824
- :param x: an [N x C x ...] Tensor of inputs.
825
- :param timesteps: a 1-D batch of timesteps.
826
- :param context: conditioning plugged in via crossattn
827
- :param y: an [N] Tensor of labels, if class-conditional.
828
- :return: an [N x C x ...] Tensor of outputs.
829
- """
830
- assert (y is not None) == (
831
- self.num_classes is not None
832
- ), "must specify y if and only if the model is class-conditional"
833
- hs = []
834
- t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
835
- emb = self.time_embed(t_emb)
836
-
837
- if self.num_classes is not None:
838
- assert y.shape[0] == x.shape[0]
839
- emb = emb + self.label_emb(y)
840
-
841
- h = x.type(self.dtype)
842
- for module in self.input_blocks:
843
- h = module(h, emb, context)
844
- hs.append(h)
845
- h = self.middle_block(h, emb, context)
846
- for module in self.output_blocks:
847
- h = th.cat([h, hs.pop()], dim=1)
848
- h = module(h, emb, context)
849
- h = h.type(x.dtype)
850
- if self.predict_codebook_ids:
851
- return self.id_predictor(h)
852
- else:
853
- return self.out(h)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/modules/diffusionmodules/util.py DELETED
@@ -1,270 +0,0 @@
1
- # adopted from
2
- # https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
3
- # and
4
- # https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
5
- # and
6
- # https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
7
- #
8
- # thanks!
9
-
10
-
11
- import os
12
- import math
13
- import torch
14
- import torch.nn as nn
15
- import numpy as np
16
- from einops import repeat
17
-
18
- from ldm.util import instantiate_from_config
19
-
20
-
21
- def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
22
- if schedule == "linear":
23
- betas = (
24
- torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
25
- )
26
-
27
- elif schedule == "cosine":
28
- timesteps = (
29
- torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
30
- )
31
- alphas = timesteps / (1 + cosine_s) * np.pi / 2
32
- alphas = torch.cos(alphas).pow(2)
33
- alphas = alphas / alphas[0]
34
- betas = 1 - alphas[1:] / alphas[:-1]
35
- betas = np.clip(betas, a_min=0, a_max=0.999)
36
-
37
- elif schedule == "sqrt_linear":
38
- betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
39
- elif schedule == "sqrt":
40
- betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
41
- else:
42
- raise ValueError(f"schedule '{schedule}' unknown.")
43
- return betas.numpy()
44
-
45
-
46
- def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
47
- if ddim_discr_method == 'uniform':
48
- c = num_ddpm_timesteps // num_ddim_timesteps
49
- ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
50
- elif ddim_discr_method == 'quad':
51
- ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
52
- else:
53
- raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
54
-
55
- # assert ddim_timesteps.shape[0] == num_ddim_timesteps
56
- # add one to get the final alpha values right (the ones from first scale to data during sampling)
57
- steps_out = ddim_timesteps + 1
58
- if verbose:
59
- print(f'Selected timesteps for ddim sampler: {steps_out}')
60
- return steps_out
61
-
62
-
63
- def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
64
- # select alphas for computing the variance schedule
65
- alphas = alphacums[ddim_timesteps]
66
- alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
67
-
68
- # according the the formula provided in https://arxiv.org/abs/2010.02502
69
- sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
70
- if verbose:
71
- print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
72
- print(f'For the chosen value of eta, which is {eta}, '
73
- f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
74
- return sigmas, alphas, alphas_prev
75
-
76
-
77
- def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
78
- """
79
- Create a beta schedule that discretizes the given alpha_t_bar function,
80
- which defines the cumulative product of (1-beta) over time from t = [0,1].
81
- :param num_diffusion_timesteps: the number of betas to produce.
82
- :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
83
- produces the cumulative product of (1-beta) up to that
84
- part of the diffusion process.
85
- :param max_beta: the maximum beta to use; use values lower than 1 to
86
- prevent singularities.
87
- """
88
- betas = []
89
- for i in range(num_diffusion_timesteps):
90
- t1 = i / num_diffusion_timesteps
91
- t2 = (i + 1) / num_diffusion_timesteps
92
- betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
93
- return np.array(betas)
94
-
95
-
96
- def extract_into_tensor(a, t, x_shape):
97
- b, *_ = t.shape
98
- out = a.gather(-1, t)
99
- return out.reshape(b, *((1,) * (len(x_shape) - 1)))
100
-
101
-
102
- def checkpoint(func, inputs, params, flag):
103
- """
104
- Evaluate a function without caching intermediate activations, allowing for
105
- reduced memory at the expense of extra compute in the backward pass.
106
- :param func: the function to evaluate.
107
- :param inputs: the argument sequence to pass to `func`.
108
- :param params: a sequence of parameters `func` depends on but does not
109
- explicitly take as arguments.
110
- :param flag: if False, disable gradient checkpointing.
111
- """
112
- if flag:
113
- args = tuple(inputs) + tuple(params)
114
- return CheckpointFunction.apply(func, len(inputs), *args)
115
- else:
116
- return func(*inputs)
117
-
118
-
119
- class CheckpointFunction(torch.autograd.Function):
120
- @staticmethod
121
- def forward(ctx, run_function, length, *args):
122
- ctx.run_function = run_function
123
- ctx.input_tensors = list(args[:length])
124
- ctx.input_params = list(args[length:])
125
- ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(),
126
- "dtype": torch.get_autocast_gpu_dtype(),
127
- "cache_enabled": torch.is_autocast_cache_enabled()}
128
- with torch.no_grad():
129
- output_tensors = ctx.run_function(*ctx.input_tensors)
130
- return output_tensors
131
-
132
- @staticmethod
133
- def backward(ctx, *output_grads):
134
- ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
135
- with torch.enable_grad(), \
136
- torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
137
- # Fixes a bug where the first op in run_function modifies the
138
- # Tensor storage in place, which is not allowed for detach()'d
139
- # Tensors.
140
- shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
141
- output_tensors = ctx.run_function(*shallow_copies)
142
- input_grads = torch.autograd.grad(
143
- output_tensors,
144
- ctx.input_tensors + ctx.input_params,
145
- output_grads,
146
- allow_unused=True,
147
- )
148
- del ctx.input_tensors
149
- del ctx.input_params
150
- del output_tensors
151
- return (None, None) + input_grads
152
-
153
-
154
- def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
155
- """
156
- Create sinusoidal timestep embeddings.
157
- :param timesteps: a 1-D Tensor of N indices, one per batch element.
158
- These may be fractional.
159
- :param dim: the dimension of the output.
160
- :param max_period: controls the minimum frequency of the embeddings.
161
- :return: an [N x dim] Tensor of positional embeddings.
162
- """
163
- if not repeat_only:
164
- half = dim // 2
165
- freqs = torch.exp(
166
- -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
167
- ).to(device=timesteps.device)
168
- args = timesteps[:, None].float() * freqs[None]
169
- embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
170
- if dim % 2:
171
- embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
172
- else:
173
- embedding = repeat(timesteps, 'b -> b d', d=dim)
174
- return embedding
175
-
176
-
177
- def zero_module(module):
178
- """
179
- Zero out the parameters of a module and return it.
180
- """
181
- for p in module.parameters():
182
- p.detach().zero_()
183
- return module
184
-
185
-
186
- def scale_module(module, scale):
187
- """
188
- Scale the parameters of a module and return it.
189
- """
190
- for p in module.parameters():
191
- p.detach().mul_(scale)
192
- return module
193
-
194
-
195
- def mean_flat(tensor):
196
- """
197
- Take the mean over all non-batch dimensions.
198
- """
199
- return tensor.mean(dim=list(range(1, len(tensor.shape))))
200
-
201
-
202
- def normalization(channels):
203
- """
204
- Make a standard normalization layer.
205
- :param channels: number of input channels.
206
- :return: an nn.Module for normalization.
207
- """
208
- return GroupNorm32(32, channels)
209
-
210
-
211
- # PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
212
- class SiLU(nn.Module):
213
- def forward(self, x):
214
- return x * torch.sigmoid(x)
215
-
216
-
217
- class GroupNorm32(nn.GroupNorm):
218
- def forward(self, x):
219
- return super().forward(x.float()).type(x.dtype)
220
-
221
- def conv_nd(dims, *args, **kwargs):
222
- """
223
- Create a 1D, 2D, or 3D convolution module.
224
- """
225
- if dims == 1:
226
- return nn.Conv1d(*args, **kwargs)
227
- elif dims == 2:
228
- return nn.Conv2d(*args, **kwargs)
229
- elif dims == 3:
230
- return nn.Conv3d(*args, **kwargs)
231
- raise ValueError(f"unsupported dimensions: {dims}")
232
-
233
-
234
- def linear(*args, **kwargs):
235
- """
236
- Create a linear module.
237
- """
238
- return nn.Linear(*args, **kwargs)
239
-
240
-
241
- def avg_pool_nd(dims, *args, **kwargs):
242
- """
243
- Create a 1D, 2D, or 3D average pooling module.
244
- """
245
- if dims == 1:
246
- return nn.AvgPool1d(*args, **kwargs)
247
- elif dims == 2:
248
- return nn.AvgPool2d(*args, **kwargs)
249
- elif dims == 3:
250
- return nn.AvgPool3d(*args, **kwargs)
251
- raise ValueError(f"unsupported dimensions: {dims}")
252
-
253
-
254
- class HybridConditioner(nn.Module):
255
-
256
- def __init__(self, c_concat_config, c_crossattn_config):
257
- super().__init__()
258
- self.concat_conditioner = instantiate_from_config(c_concat_config)
259
- self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
260
-
261
- def forward(self, c_concat, c_crossattn):
262
- c_concat = self.concat_conditioner(c_concat)
263
- c_crossattn = self.crossattn_conditioner(c_crossattn)
264
- return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
265
-
266
-
267
- def noise_like(shape, device, repeat=False):
268
- repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
269
- noise = lambda: torch.randn(shape, device=device)
270
- return repeat_noise() if repeat else noise()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Control-Color/ldm/modules/distributions/__init__.py DELETED
File without changes
Control-Color/ldm/modules/distributions/__pycache__/__init__.cpython-38.pyc DELETED
Binary file (167 Bytes)