mridulk commited on
Commit
d39ef0a
·
1 Parent(s): 17191f4

added models

Browse files
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ *__pycache__/*
ldm/models/LSFautoencoder.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from scripts.constants import BASERECLOSS
2
+ import torch
3
+ from torch import nn
4
+ import torch.nn.functional as F
5
+ import pytorch_lightning as pl
6
+ from ldm.models.M_ModelAE_Cnn import CnnVae as LSFDisentangler
7
+
8
+ from main import instantiate_from_config
9
+
10
+ # from ldm.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
11
+ from ldm.models.autoencoder import VQModel
12
+
13
+ from torchinfo import summary
14
+ import collections
15
+
16
+ import torchvision.utils as vutils
17
+
18
+
19
+ LSFLOCONFIG_KEY = "LSF_params"
20
+ BASEMODEL_KEY = "basemodel"
21
+
22
+ VQGAN_MODEL_INPUT = 'image'
23
+
24
+ DISENTANGLER_DECODER_OUTPUT = 'output'
25
+ DISENTANGLER_ENCODER_INPUT = 'in'
26
+ DISENTANGLER_CLASS_OUTPUT = 'class'
27
+ DISENTANGLER_ATTRIBUTE_OUTPUT = 'attribute'
28
+ DISENTANGLER_EMBEDDING = 'embedding'
29
+
30
+
31
+ class LSFVQVAE(VQModel):
32
+ def __init__(self, **args):
33
+ print(args)
34
+
35
+ self.save_hyperparameters()
36
+
37
+ LSF_args = args[LSFLOCONFIG_KEY]
38
+ del args[LSFLOCONFIG_KEY]
39
+
40
+ super().__init__(**args)
41
+
42
+ self.freeze()
43
+
44
+ ckpt_path = LSF_args.get('ckpt_path', None)
45
+ if 'ckpt_path' in LSF_args:
46
+ del LSF_args['ckpt_path']
47
+
48
+ self.LSF_disentangler = LSFDisentangler(**LSF_args)
49
+ LSF_args['ckpt_path'] = ckpt_path
50
+
51
+ if ckpt_path is not None:
52
+ self.init_from_ckpt(ckpt_path, ignore_keys=[])
53
+ print('Loaded trained model at', ckpt_path)
54
+
55
+ self.verbose = LSF_args.get('verbose', False)
56
+ # self.verbose = True
57
+
58
+ def encode(self, x):
59
+ encoder_out = self.encoder(x)
60
+ disentangler_outputs = self.LSF_disentangler(encoder_out)
61
+ disentangler_out = disentangler_outputs[DISENTANGLER_DECODER_OUTPUT]
62
+ h = self.quant_conv(disentangler_out)
63
+ quant, base_quantizer_loss, info = self.quantize(h)
64
+
65
+ base_loss_dic = {'quantizer_loss': base_quantizer_loss}
66
+ in_out_disentangler = {
67
+ DISENTANGLER_ENCODER_INPUT: encoder_out,
68
+ }
69
+ in_out_disentangler = {**in_out_disentangler, **disentangler_outputs}
70
+
71
+ return quant, base_loss_dic, in_out_disentangler, info
72
+
73
+ def forward(self, input):
74
+ quant, base_loss_dic, in_out_disentangler, _ = self.encode(input)
75
+ dec = self.decode(quant)
76
+ return dec, base_loss_dic, in_out_disentangler
77
+
78
+ def forward_hypothetical(self, input):
79
+ encoder_out = self.encoder(input)
80
+ h = self.quant_conv(encoder_out)
81
+ quant, base_hypothetical_quantizer_loss, info = self.quantize(h)
82
+ dec = self.decode(quant)
83
+ return dec, base_hypothetical_quantizer_loss
84
+
85
+ def step(self, batch, batch_idx, prefix):
86
+ x = self.get_input(batch, self.image_key)
87
+ xrec, base_loss_dic, in_out_disentangler = self(x)
88
+
89
+ if self.verbose:
90
+ xrec_hypthetical, base_hypothetical_quantizer_loss = self.forward_hypothetical(x)
91
+ hypothetical_rec_loss =torch.mean(torch.abs(x.contiguous() - xrec_hypthetical.contiguous()))
92
+ self.log(prefix+"/base_hypothetical_rec_loss", hypothetical_rec_loss, prog_bar=False, logger=True, on_step=False, on_epoch=True)
93
+ self.log(prefix+"/base_hypothetical_quantizer_loss", base_hypothetical_quantizer_loss, prog_bar=False, logger=True, on_step=False, on_epoch=True)
94
+
95
+ # base losses
96
+ true_rec_loss = torch.mean(torch.abs(x.contiguous() - xrec.contiguous()))
97
+ self.log(prefix+ BASERECLOSS, true_rec_loss, prog_bar=False, logger=True, on_step=False, on_epoch=True)
98
+ self.log(prefix+"/base_quantizer_loss", base_loss_dic['quantizer_loss'], prog_bar=False, logger=True, on_step=False, on_epoch=True)
99
+
100
+ total_loss, LSF_losses_dict = self.LSF_disentangler.loss(in_out_disentangler[DISENTANGLER_DECODER_OUTPUT], in_out_disentangler[DISENTANGLER_ENCODER_INPUT],
101
+ batch['class'], in_out_disentangler['embedding'], in_out_disentangler['vae_mu'], in_out_disentangler['vae_logvar'])
102
+
103
+ if self.verbose:
104
+ self.log(prefix+"/disentangler_total_loss", total_loss, prog_bar=False, logger=True, on_step=True, on_epoch=True)
105
+ for i in LSF_losses_dict:
106
+ if "_f1" in i:
107
+ self.log(prefix+"/disentangler_LSF_"+i, LSF_losses_dict[i], prog_bar=False, logger=True, on_step=True, on_epoch=True)
108
+
109
+ self.log(prefix+"/disentangler_total_loss", total_loss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
110
+ for i in LSF_losses_dict:
111
+ self.log(prefix+"/disentangler_LSF_"+i, LSF_losses_dict[i], prog_bar=True, logger=True, on_step=True, on_epoch=True)
112
+
113
+ self.log(prefix+"/disentangler_learning_rate", self.LSF_disentangler.learning_rate, prog_bar=False, logger=True, on_step=False, on_epoch=True)
114
+
115
+ # monitor for checkpoint saving is set on this
116
+ self.log(prefix+"/rec_loss", LSF_losses_dict['L_rec'], prog_bar=True, logger=True, on_step=True, on_epoch=True)
117
+
118
+ return total_loss
119
+
120
+ def training_step(self, batch, batch_idx):
121
+ return self.step(batch, batch_idx, 'train')
122
+
123
+
124
+ def validation_step(self, batch, batch_idx):
125
+ return self.step(batch, batch_idx, 'val')
126
+
127
+ def configure_optimizers(self):
128
+ lr = self.LSF_disentangler.learning_rate
129
+ opt_ae = torch.optim.Adam(self.LSF_disentangler.parameters(), lr=lr)
130
+
131
+ return [opt_ae], []
132
+
133
+ def image2encoding(self, x):
134
+ encoder_out = self.encoder(x)
135
+ mu, logvar = self.LSF_disentangler.encode(encoder_out)
136
+ z = self.LSF_disentangler.reparameterize(mu, logvar)
137
+ return z, mu, logvar
138
+
139
+ def encoding2image(self, z):
140
+ disentangler_out = self.LSF_disentangler.decoder(z)
141
+ h = self.quant_conv(disentangler_out)
142
+ quant, base_quantizer_loss, info = self.quantize(h)
143
+ rec = self.decode(quant)
144
+ return rec
ldm/models/M_ModelAE_Cnn.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Source: https://github.com/lissomx/MSP/blob/master/M_ModelAE_Cnn.py
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from torch.nn import functional as F
6
+ import numpy as np
7
+
8
+ class Encoder(nn.Module):
9
+ # only for square pics with width or height is n^(2x)
10
+ def __init__(self, image_size, nf, hidden_size=None, nc=3):
11
+ super(Encoder, self).__init__()
12
+ self.image_size = image_size
13
+ self.hidden_size = hidden_size
14
+ sequens = [
15
+ nn.Conv2d(nc, nf, 4, 2, 1, bias=False),
16
+ nn.LeakyReLU(0.2, inplace=True),
17
+ ]
18
+ while(True):
19
+ image_size = image_size/2
20
+ if image_size > 4:
21
+ sequens.append(nn.Conv2d(nf, nf * 2, 4, 2, 1, bias=False))
22
+ sequens.append(nn.BatchNorm2d(nf * 2))
23
+ sequens.append(nn.LeakyReLU(0.2, inplace=True))
24
+ nf = nf * 2
25
+ else:
26
+ if hidden_size is None:
27
+ self.hidden_size = int(nf)
28
+ sequens.append(nn.Conv2d(nf, self.hidden_size, int(image_size), 1, 0, bias=False))
29
+ break
30
+ self.main = nn.Sequential(*sequens)
31
+
32
+ def forward(self, input):
33
+ return self.main(input).squeeze(3).squeeze(2)
34
+
35
+
36
+ class Decoder(nn.Module):
37
+ # only for square pics with width or height is n^(2x)
38
+ def __init__(self, image_size, nf, hidden_size=None, nc=3):
39
+ super(Decoder, self).__init__()
40
+ self.image_size = image_size
41
+ self.hidden_size = hidden_size
42
+ sequens = [
43
+ nn.Tanh(),
44
+ nn.ConvTranspose2d(nf, nc, 4, 2, 1, bias=False),
45
+ ]
46
+ while(True):
47
+ image_size = image_size/2
48
+ sequens.append(nn.ReLU(True))
49
+ sequens.append(nn.BatchNorm2d(nf))
50
+ if image_size > 4:
51
+ sequens.append(nn.ConvTranspose2d(nf * 2, nf, 4, 2, 1, bias=False))
52
+ else:
53
+ if hidden_size is None:
54
+ self.hidden_size = int(nf)
55
+ sequens.append(nn.ConvTranspose2d(self.hidden_size, nf, int(image_size), 1, 0, bias=False))
56
+ break
57
+ nf = nf*2
58
+ sequens.reverse()
59
+ self.main = nn.Sequential(*sequens)
60
+
61
+ def forward(self, z):
62
+ z = z.unsqueeze(2).unsqueeze(2)
63
+ output = self.main(z)
64
+ return output
65
+
66
+ def loss(self, predict, orig):
67
+ batch_size = predict.shape[0]
68
+ a = predict.view(batch_size, -1)
69
+ b = orig.view(batch_size, -1)
70
+ L = F.mse_loss(a, b, reduction='sum')
71
+ return L
72
+
73
+
74
+ class CnnVae(nn.Module):
75
+ def __init__(self, learning_rate, image_size, label_size, nf, hidden_size=None, nc=3):
76
+ super(CnnVae, self).__init__()
77
+ self.encoder = Encoder(image_size, nf, hidden_size, nc)
78
+ self.decoder = Decoder(image_size, nf, hidden_size, nc)
79
+ self.image_size = image_size
80
+ self.nc = nc
81
+ self.label_size = label_size
82
+ self.hidden_size = self.encoder.hidden_size
83
+
84
+ self.learning_rate = learning_rate
85
+
86
+ self.fc1 = nn.Linear(self.hidden_size, self.hidden_size)
87
+ self.fc2 = nn.Linear(self.hidden_size, self.hidden_size)
88
+
89
+ self.M = nn.Parameter(torch.empty(label_size, self.hidden_size))
90
+ nn.init.xavier_normal_(self.M)
91
+
92
+ def encode(self, x):
93
+ h = self.encoder(x)
94
+ mu = self.fc1(h)
95
+ logvar = self.fc2(h)
96
+ return mu, logvar
97
+
98
+ def reparameterize(self, mu, logvar):
99
+ std = torch.exp(0.5*logvar)
100
+ eps = torch.randn_like(std)
101
+ return mu + eps*std
102
+
103
+ def forward(self, x):
104
+ # breakpoint()
105
+ mu, logvar = self.encode(x)
106
+ z = self.reparameterize(mu, logvar)
107
+ prod = self.decoder(z)
108
+ outputs = {'output': prod} # DISENTANGLER_DECODER_OUTPUT
109
+ # outputs[DISENTANGLER_ATTRIBUTE_OUTPUT] = attr
110
+ outputs['embedding'] = z
111
+ outputs['vae_mu'] = mu
112
+ outputs['vae_logvar'] = logvar
113
+ # return prod, z, mu, logvar
114
+ return outputs
115
+
116
+ def _loss_vae(self, mu, logvar):
117
+ # https://arxiv.org/abs/1312.6114
118
+ # KLD = 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
119
+ KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
120
+ return KLD
121
+
122
+ def _loss_msp(self, label, z):
123
+
124
+ labels_one_hot = F.one_hot(label, num_classes=self.label_size)
125
+ labels_one_hot = labels_one_hot.to(dtype=torch.float32)
126
+ labels_one_hot[labels_one_hot == 0.0] = -1
127
+
128
+ L1 = F.mse_loss((z @ self.M.t()).view(-1), labels_one_hot.view(-1), reduction="none").sum()
129
+ L2 = F.mse_loss((labels_one_hot @ self.M).view(-1), z.view(-1), reduction="none").sum()
130
+ return L1 + L2, L1, L2
131
+
132
+ def loss(self, prod, orgi, label, z, mu, logvar):
133
+ L_rec = self.decoder.loss(prod, orgi)
134
+ L_vae = self._loss_vae(mu, logvar)
135
+ L_msp, L1_msp, L2_msp = self._loss_msp(label, z)
136
+ _msp_weight = orgi.numel()/(label.numel()+z.numel())
137
+ Loss = L_rec + L_vae + L_msp * _msp_weight
138
+ loss_dict = {'L1': L1_msp, 'L2': L2_msp, 'L_msp': L_msp,
139
+ 'L_rec': L_rec, 'L_vae': L_vae}
140
+ return Loss, loss_dict #L_rec.item(), L_vae.item(), L_msp.item()
141
+
142
+ def acc(self, z, l):
143
+ zl = z @ self.M.t()
144
+ a = zl.clamp(-1, 1)*l*0.5+0.5
145
+ return a.round().mean().item()
146
+
147
+ def predict(self, x, new_ls=None, weight=1.0):
148
+ z, _ = self.encode(x)
149
+ if new_ls is not None:
150
+ zl = z @ self.M.t()
151
+ d = torch.zeros_like(zl)
152
+ for i, v in new_ls:
153
+ d[:,i] = v*weight - zl[:,i]
154
+ z += d @ self.M
155
+ prod = self.decoder(z)
156
+ return prod
157
+
158
+ def predict_ex(self, x, label, new_ls=None, weight=1.0):
159
+ return self.predict(x,new_ls,weight)
160
+
161
+
162
+
163
+ def get_U(self, eps=1e-5):
164
+
165
+ from scipy import linalg, compress
166
+
167
+ # get the null matrix N of M
168
+ # such that U=[M;N] is orthogonal
169
+ M = self.M.detach().cpu()
170
+ A = torch.zeros(M.shape[1]-M.shape[0], M.shape[1])
171
+ A = torch.cat([M, A])
172
+ u, s, vh = linalg.svd(A.numpy())
173
+ null_mask = (s <= eps)
174
+ null_space = compress(null_mask, vh, axis=0)
175
+ N = torch.tensor(null_space)
176
+ return torch.cat([self.M, N.to(self.M.device)])
177
+
178
+
179
+
ldm/models/__pycache__/LSFautoencoder.cpython-38.pyc ADDED
Binary file (4.66 kB). View file
 
ldm/models/__pycache__/M_ModelAE_Cnn.cpython-38.pyc ADDED
Binary file (5.78 kB). View file
 
ldm/models/__pycache__/autoencoder.cpython-38.pyc ADDED
Binary file (15.3 kB). View file
 
ldm/models/__pycache__/cwautoencoder.cpython-38.pyc ADDED
Binary file (6.91 kB). View file
 
ldm/models/__pycache__/vqgan_dual.cpython-38.pyc ADDED
Binary file (6.78 kB). View file
 
ldm/models/__pycache__/vqgan_dual_non_dict.cpython-38.pyc ADDED
Binary file (8.12 kB). View file
 
ldm/models/autoencoder.py ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
7
+ from ldm.modules.diffusionmodules.model import Encoder, Decoder
8
+ from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
9
+ from ldm.models.disentanglement.iterative_normalization import IterNormRotation as cw_layer
10
+
11
+ from ldm.util import instantiate_from_config
12
+
13
+
14
+ import os
15
+ import itertools
16
+ import numpy as np
17
+ import pandas as pd
18
+ from ldm.analysis_utils import get_CosineDistance_matrix, aggregatefrom_specimen_to_species
19
+ from ldm.plotting_utils import plot_heatmap_at_path
20
+
21
+ class VQModel(pl.LightningModule):
22
+ def __init__(self,
23
+ ddconfig,
24
+ lossconfig,
25
+ n_embed,
26
+ embed_dim,
27
+ ckpt_path=None,
28
+ cw_module_infer=False,
29
+ ignore_keys=[],
30
+ image_key="image",
31
+ colorize_nlabels=None,
32
+ monitor=None,
33
+ batch_resize_range=None,
34
+ scheduler_config=None,
35
+ lr_g_factor=1.0,
36
+ remap=None,
37
+ sane_index_shape=False, # tell vector quantizer to return indices as bhw
38
+ use_ema=False
39
+ ):
40
+ super().__init__()
41
+ self.embed_dim = embed_dim
42
+ self.n_embed = n_embed
43
+ self.image_key = image_key
44
+ self.cw_module_infer = cw_module_infer
45
+ self.encoder = Encoder(**ddconfig)
46
+ self.decoder = Decoder(**ddconfig)
47
+ if self.cw_module_infer:
48
+ self.encoder.norm_out = cw_layer(self.encoder.block_in)
49
+ print("Changed to cw layer before loading cw model")
50
+ self.loss = instantiate_from_config(lossconfig)
51
+ self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25,
52
+ remap=remap,
53
+ sane_index_shape=sane_index_shape)
54
+ self.quant_conv = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
55
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
56
+ if colorize_nlabels is not None:
57
+ assert type(colorize_nlabels)==int
58
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
59
+ if monitor is not None:
60
+ self.monitor = monitor
61
+ self.batch_resize_range = batch_resize_range
62
+ if self.batch_resize_range is not None:
63
+ print(f"{self.__class__.__name__}: Using per-batch resizing in range {batch_resize_range}.")
64
+
65
+ self.use_ema = use_ema
66
+ if self.use_ema:
67
+ self.model_ema = LitEma(self)
68
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
69
+
70
+ if ckpt_path is not None:
71
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
72
+ self.scheduler_config = scheduler_config
73
+ self.lr_g_factor = lr_g_factor
74
+
75
+ @contextmanager
76
+ def ema_scope(self, context=None):
77
+ if self.use_ema:
78
+ self.model_ema.store(self.parameters())
79
+ self.model_ema.copy_to(self)
80
+ if context is not None:
81
+ print(f"{context}: Switched to EMA weights")
82
+ try:
83
+ yield None
84
+ finally:
85
+ if self.use_ema:
86
+ self.model_ema.restore(self.parameters())
87
+ if context is not None:
88
+ print(f"{context}: Restored training weights")
89
+
90
+ def init_from_ckpt(self, path, ignore_keys=list()):
91
+ sd = torch.load(path, map_location="cpu")["state_dict"]
92
+ keys = list(sd.keys())
93
+ for k in keys:
94
+ for ik in ignore_keys:
95
+ if k.startswith(ik):
96
+ print("Deleting key {} from state_dict.".format(k))
97
+ del sd[k]
98
+ missing, unexpected = self.load_state_dict(sd, strict=False)
99
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
100
+ if len(missing) > 0:
101
+ print(f"Missing Keys: {missing}")
102
+ print(f"Unexpected Keys: {unexpected}")
103
+
104
+ def on_train_batch_end(self, *args, **kwargs):
105
+ if self.use_ema:
106
+ self.model_ema(self)
107
+
108
+ def encode(self, x):
109
+ h = self.encoder(x)
110
+ h = self.quant_conv(h)
111
+ quant, emb_loss, info = self.quantize(h)
112
+ return quant, emb_loss, info
113
+
114
+ def encode_to_prequant(self, x):
115
+ h = self.encoder(x)
116
+ h = self.quant_conv(h)
117
+ return h
118
+
119
+ def decode(self, quant):
120
+ quant = self.post_quant_conv(quant)
121
+ dec = self.decoder(quant)
122
+ return dec
123
+
124
+ def decode_code(self, code_b):
125
+ quant_b = self.quantize.embed_code(code_b)
126
+ dec = self.decode(quant_b)
127
+ return dec
128
+
129
+ def forward(self, input, return_pred_indices=False):
130
+ quant, diff, (_,_,ind) = self.encode(input)
131
+ dec = self.decode(quant)
132
+ if return_pred_indices:
133
+ return dec, diff, ind
134
+ return dec, diff
135
+
136
+ def get_input(self, batch, k):
137
+ x = batch[k]
138
+ if len(x.shape) == 3:
139
+ x = x[..., None]
140
+ x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
141
+ if self.batch_resize_range is not None:
142
+ lower_size = self.batch_resize_range[0]
143
+ upper_size = self.batch_resize_range[1]
144
+ if self.global_step <= 4:
145
+ # do the first few batches with max size to avoid later oom
146
+ new_resize = upper_size
147
+ else:
148
+ new_resize = np.random.choice(np.arange(lower_size, upper_size+16, 16))
149
+ if new_resize != x.shape[2]:
150
+ x = F.interpolate(x, size=new_resize, mode="bicubic")
151
+ x = x.detach()
152
+ return x
153
+
154
+ def training_step(self, batch, batch_idx, optimizer_idx):
155
+ # https://github.com/pytorch/pytorch/issues/37142
156
+ # try not to fool the heuristics
157
+ x = self.get_input(batch, self.image_key)
158
+ # xrec, qloss, ind = self(x, return_pred_indices=True)
159
+ xrec, qloss = self(x, return_pred_indices=False)
160
+
161
+ if optimizer_idx == 0:
162
+ # autoencode
163
+ aeloss, log_dict_ae = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
164
+ last_layer=self.get_last_layer(), split="train")
165
+
166
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
167
+ return aeloss
168
+
169
+ if optimizer_idx == 1:
170
+ # discriminator
171
+ discloss, log_dict_disc = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
172
+ last_layer=self.get_last_layer(), split="train")
173
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True)
174
+ return discloss
175
+
176
+ def validation_step(self, batch, batch_idx):
177
+ log_dict = self._validation_step(batch, batch_idx)
178
+ with self.ema_scope():
179
+ log_dict_ema = self._validation_step(batch, batch_idx, suffix="_ema")
180
+ return log_dict
181
+
182
+ def _validation_step(self, batch, batch_idx, suffix=""):
183
+ x = self.get_input(batch, self.image_key)
184
+ # xrec, qloss, ind = self(x, return_pred_indices=True)
185
+ xrec, qloss = self(x, return_pred_indices=False)
186
+ aeloss, log_dict_ae = self.loss(qloss, x, xrec, 0,
187
+ self.global_step,
188
+ last_layer=self.get_last_layer(),
189
+ split="val"+suffix
190
+ )
191
+
192
+ discloss, log_dict_disc = self.loss(qloss, x, xrec, 1,
193
+ self.global_step,
194
+ last_layer=self.get_last_layer(),
195
+ split="val"+suffix
196
+ )
197
+ rec_loss = log_dict_ae[f"val{suffix}/rec_loss"]
198
+ self.log(f"val{suffix}/rec_loss", rec_loss,
199
+ prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
200
+ self.log(f"val{suffix}/aeloss", aeloss,
201
+ prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
202
+ # if version.parse(pl.__version__) >= version.parse('1.4.0'):
203
+ # del log_dict_ae[f"val{suffix}/rec_loss"]
204
+ self.log_dict(log_dict_ae)
205
+ self.log_dict(log_dict_disc)
206
+ return self.log_dict
207
+
208
+ def configure_optimizers(self):
209
+ lr_d = self.learning_rate
210
+ lr_g = self.lr_g_factor*self.learning_rate
211
+ print("lr_d", lr_d)
212
+ print("lr_g", lr_g)
213
+ opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
214
+ list(self.decoder.parameters())+
215
+ list(self.quantize.parameters())+
216
+ list(self.quant_conv.parameters())+
217
+ list(self.post_quant_conv.parameters()),
218
+ lr=lr_g, betas=(0.5, 0.9))
219
+ opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
220
+ lr=lr_d, betas=(0.5, 0.9))
221
+
222
+ if self.scheduler_config is not None:
223
+ scheduler = instantiate_from_config(self.scheduler_config)
224
+
225
+ print("Setting up LambdaLR scheduler...")
226
+ scheduler = [
227
+ {
228
+ 'scheduler': LambdaLR(opt_ae, lr_lambda=scheduler.schedule),
229
+ 'interval': 'step',
230
+ 'frequency': 1
231
+ },
232
+ {
233
+ 'scheduler': LambdaLR(opt_disc, lr_lambda=scheduler.schedule),
234
+ 'interval': 'step',
235
+ 'frequency': 1
236
+ },
237
+ ]
238
+ return [opt_ae, opt_disc], scheduler
239
+ return [opt_ae, opt_disc], []
240
+
241
+ def get_last_layer(self):
242
+ return self.decoder.conv_out.weight
243
+
244
+ def log_images(self, batch, only_inputs=False, plot_ema=False, **kwargs):
245
+ log = dict()
246
+ x = self.get_input(batch, self.image_key)
247
+ x = x.to(self.device)
248
+ if only_inputs:
249
+ log["inputs"] = x
250
+ return log
251
+ # xrec, _ = self(x)
252
+ xrec = self(x)[0]
253
+ if x.shape[1] > 3:
254
+ # colorize with random projection
255
+ assert xrec.shape[1] > 3
256
+ x = self.to_rgb(x)
257
+ xrec = self.to_rgb(xrec)
258
+ log["inputs"] = x
259
+ log["reconstructions"] = xrec
260
+ if plot_ema:
261
+ with self.ema_scope():
262
+ xrec_ema, _ = self(x)
263
+ if x.shape[1] > 3: xrec_ema = self.to_rgb(xrec_ema)
264
+ log["reconstructions_ema"] = xrec_ema
265
+ return log
266
+
267
+ def to_rgb(self, x):
268
+ assert self.image_key == "segmentation"
269
+ if not hasattr(self, "colorize"):
270
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
271
+ x = F.conv2d(x, weight=self.colorize)
272
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
273
+ return x
274
+
275
+ # @torch.no_grad()
276
+ # def test_step(self, batch, batch_idx):
277
+ # x = self.get_input(batch, self.image_key)
278
+ # h = self.encoder(x)
279
+ # h = self.quant_conv(h)
280
+ # class_label = batch['class']
281
+
282
+ # return {'z_cw': h,
283
+ # 'label': class_label,
284
+ # 'class_name': batch['class_name']}
285
+
286
+ # # NOTE: This is kinda hacky. But ok for now for test purposes.
287
+ # def set_test_chkpt_path(self, chkpt_path):
288
+ # self.test_chkpt_path = chkpt_path
289
+
290
+ # @torch.no_grad()
291
+ # def test_epoch_end(self, in_out):
292
+ # postfix_name = 'inference_false'
293
+ # z_cw =torch.cat([x['z_cw'] for x in in_out], 0)
294
+ # labels =torch.cat([x['label'] for x in in_out], 0)
295
+ # sorting_indices = np.argsort(labels.cpu())
296
+ # sorted_zq_cw = z_cw[sorting_indices, :]
297
+
298
+ # classnames = list(itertools.chain.from_iterable([x['class_name'] for x in in_out]))
299
+ # sorted_class_names_according_to_class_indx = [classnames[i] for i in sorting_indices]
300
+ # z_size = sorted_zq_cw.shape[-1]
301
+ # channels = sorted_zq_cw.shape[1]
302
+ # # breakpoint()
303
+ # figs_folder = os.path.join('/', *self.test_chkpt_path.split('/')[:-2], 'figs/testset_agg')
304
+ # if not os.path.exists(figs_folder):
305
+ # os.makedirs(figs_folder)
306
+
307
+
308
+
309
+ # sorted_zq_cw_aggregated = aggregatefrom_specimen_to_species(sorted_class_names_according_to_class_indx, sorted_zq_cw, z_size, channels)
310
+ # z_cosine_distances = get_CosineDistance_matrix(sorted_zq_cw_aggregated)
311
+
312
+ # plot_heatmap_at_path(z_cosine_distances.cpu(), figs_folder, self.test_chkpt_path, title=f'Cosine_distances_{postfix_name}', postfix='testset_agg')
313
+
314
+
315
+
316
+ # z_cosine_distancess_np = z_cosine_distances.cpu().numpy()
317
+ # df = pd.DataFrame(z_cosine_distancess_np)
318
+ # df = df.drop(columns=[5, 6])
319
+ # df = df.drop([5, 6])
320
+ # path_to_save = os.path.join(figs_folder, f'CW_z_cosine_distances_{postfix_name}.csv')
321
+ # print("saved to path : ", path_to_save)
322
+ # df.to_csv(path_to_save)
323
+
324
+ # return None
325
+
326
+
327
+ class VQModelInterface(VQModel):
328
+ def __init__(self, embed_dim, *args, **kwargs):
329
+ super().__init__(embed_dim=embed_dim, *args, **kwargs)
330
+ self.embed_dim = embed_dim
331
+
332
+ def encode(self, x):
333
+ h = self.encoder(x)
334
+ h = self.quant_conv(h)
335
+ return h
336
+
337
+ def decode(self, h, force_not_quantize=False):
338
+ # also go through quantization layer
339
+ if not force_not_quantize:
340
+ quant, emb_loss, info = self.quantize(h)
341
+ else:
342
+ quant = h
343
+ quant = self.post_quant_conv(quant)
344
+ dec = self.decoder(quant)
345
+ return dec
346
+
347
+ class VQModelInterfacePostQuant(VQModel):
348
+ def __init__(self, embed_dim, *args, **kwargs):
349
+ super().__init__(embed_dim=embed_dim, *args, **kwargs)
350
+ self.embed_dim = embed_dim
351
+
352
+ def encode(self, x):
353
+ h = self.encoder(x)
354
+ h = self.quant_conv(h)
355
+ quant, emb_loss, info = self.quantize(h)
356
+ return quant
357
+
358
+ def decode(self, h, force_not_quantize=False):
359
+ quant = self.post_quant_conv(h)
360
+ dec = self.decoder(quant)
361
+ return dec
362
+
363
+ class VQModelInterfacePostQuantConv(VQModel):
364
+ def __init__(self, embed_dim, *args, **kwargs):
365
+ super().__init__(embed_dim=embed_dim, *args, **kwargs)
366
+ self.embed_dim = embed_dim
367
+
368
+ def encode(self, x):
369
+ h = self.encoder(x)
370
+ h = self.quant_conv(h)
371
+ quant, emb_loss, info = self.quantize(h)
372
+ quant = self.post_quant_conv(h)
373
+ return quant
374
+
375
+ def decode(self, h, force_not_quantize=False):
376
+ dec = self.decoder(h)
377
+ return dec
378
+
379
+
380
+
381
+ class AutoencoderKL(pl.LightningModule):
382
+ def __init__(self,
383
+ ddconfig,
384
+ lossconfig,
385
+ embed_dim,
386
+ ckpt_path=None,
387
+ ignore_keys=[],
388
+ image_key="image",
389
+ cw_module_infer=False,
390
+ colorize_nlabels=None,
391
+ monitor=None
392
+ ):
393
+ super().__init__()
394
+ self.image_key = image_key
395
+ self.encoder = Encoder(**ddconfig)
396
+ self.decoder = Decoder(**ddconfig)
397
+ self.cw_module_infer = cw_module_infer
398
+ if self.cw_module_infer:
399
+ self.encoder.norm_out = cw_layer(self.encoder.block_in)
400
+ print("Changed to cw layer before loading cw model")
401
+ self.loss = instantiate_from_config(lossconfig)
402
+ assert ddconfig["double_z"]
403
+ self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
404
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
405
+ self.embed_dim = embed_dim
406
+ if colorize_nlabels is not None:
407
+ assert type(colorize_nlabels)==int
408
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
409
+ if monitor is not None:
410
+ self.monitor = monitor
411
+ if ckpt_path is not None:
412
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
413
+
414
+ def init_from_ckpt(self, path, ignore_keys=list()):
415
+ sd = torch.load(path, map_location="cpu")["state_dict"]
416
+ keys = list(sd.keys())
417
+ for k in keys:
418
+ for ik in ignore_keys:
419
+ if k.startswith(ik):
420
+ print("Deleting key {} from state_dict.".format(k))
421
+ del sd[k]
422
+ self.load_state_dict(sd, strict=False)
423
+ print(f"Restored from {path}")
424
+
425
+ def encode(self, x):
426
+ h = self.encoder(x)
427
+ moments = self.quant_conv(h)
428
+ posterior = DiagonalGaussianDistribution(moments)
429
+ return posterior
430
+
431
+ def decode(self, z):
432
+ z = self.post_quant_conv(z)
433
+ dec = self.decoder(z)
434
+ return dec
435
+
436
+ def forward(self, input, sample_posterior=True):
437
+ posterior = self.encode(input)
438
+ if sample_posterior:
439
+ z = posterior.sample()
440
+ else:
441
+ z = posterior.mode()
442
+ dec = self.decode(z)
443
+ return dec, posterior
444
+
445
+ def get_input(self, batch, k):
446
+ x = batch[k]
447
+ if len(x.shape) == 3:
448
+ x = x[..., None]
449
+ x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
450
+ return x
451
+
452
+ def training_step(self, batch, batch_idx, optimizer_idx):
453
+ inputs = self.get_input(batch, self.image_key)
454
+ reconstructions, posterior = self(inputs)
455
+
456
+ if optimizer_idx == 0:
457
+ # train encoder+decoder+logvar
458
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
459
+ last_layer=self.get_last_layer(), split="train")
460
+ self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
461
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
462
+ return aeloss
463
+
464
+ if optimizer_idx == 1:
465
+ # train the discriminator
466
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
467
+ last_layer=self.get_last_layer(), split="train")
468
+
469
+ self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
470
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
471
+ return discloss
472
+
473
+ def validation_step(self, batch, batch_idx):
474
+ inputs = self.get_input(batch, self.image_key)
475
+ reconstructions, posterior = self(inputs)
476
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
477
+ last_layer=self.get_last_layer(), split="val")
478
+
479
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
480
+ last_layer=self.get_last_layer(), split="val")
481
+
482
+ self.log("val/rec_loss", log_dict_ae["val/rec_loss"])
483
+ self.log_dict(log_dict_ae)
484
+ self.log_dict(log_dict_disc)
485
+ return self.log_dict
486
+
487
+ def configure_optimizers(self):
488
+ lr = self.learning_rate
489
+ opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
490
+ list(self.decoder.parameters())+
491
+ list(self.quant_conv.parameters())+
492
+ list(self.post_quant_conv.parameters()),
493
+ lr=lr, betas=(0.5, 0.9))
494
+ opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
495
+ lr=lr, betas=(0.5, 0.9))
496
+ return [opt_ae, opt_disc], []
497
+
498
+ def get_last_layer(self):
499
+ return self.decoder.conv_out.weight
500
+
501
+ @torch.no_grad()
502
+ def log_images(self, batch, only_inputs=False, **kwargs):
503
+ log = dict()
504
+ x = self.get_input(batch, self.image_key)
505
+ x = x.to(self.device)
506
+ if not only_inputs:
507
+ xrec, posterior = self(x)
508
+ if x.shape[1] > 3:
509
+ # colorize with random projection
510
+ assert xrec.shape[1] > 3
511
+ x = self.to_rgb(x)
512
+ xrec = self.to_rgb(xrec)
513
+ log["samples"] = self.decode(torch.randn_like(posterior.sample()))
514
+ log["reconstructions"] = xrec
515
+ log["inputs"] = x
516
+ return log
517
+
518
+ def to_rgb(self, x):
519
+ assert self.image_key == "segmentation"
520
+ if not hasattr(self, "colorize"):
521
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
522
+ x = F.conv2d(x, weight=self.colorize)
523
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
524
+ return x
525
+
526
+
527
+ class IdentityFirstStage(torch.nn.Module):
528
+ def __init__(self, *args, vq_interface=False, **kwargs):
529
+ self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff
530
+ super().__init__()
531
+
532
+ def encode(self, x, *args, **kwargs):
533
+ return x
534
+
535
+ def decode(self, x, *args, **kwargs):
536
+ return x
537
+
538
+ def quantize(self, x, *args, **kwargs):
539
+ if self.vq_interface:
540
+ return x, None, [None, None, None]
541
+ return x
542
+
543
+ def forward(self, x, *args, **kwargs):
544
+ return x
ldm/models/cwautoencoder.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import itertools
4
+ import numpy as np
5
+ import pandas as pd
6
+ import pytorch_lightning as pl
7
+ import torch.nn.functional as F
8
+
9
+ # from contextlib import contextmanager
10
+
11
+ # from ldm.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
12
+ # from ldm.modules.diffusionmodules.model import Encoder, Decoder
13
+ # from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
14
+ from ldm.models.autoencoder import VQModel, AutoencoderKL
15
+ from ldm.models.disentanglement.iterative_normalization import IterNormRotation as cw_layer
16
+ from ldm.analysis_utils import get_CosineDistance_matrix, aggregatefrom_specimen_to_species
17
+ from ldm.plotting_utils import plot_heatmap_at_path
18
+
19
+
20
+ from ldm.util import instantiate_from_config
21
+
22
+ CONCEPT_DATA_KEY = "concept_data"
23
+
24
+ class CWmodelVQGAN(VQModel):
25
+
26
+
27
+ def __init__(self, **args):
28
+ print(args)
29
+
30
+ self.save_hyperparameters()
31
+
32
+ concept_data_args = args[CONCEPT_DATA_KEY]
33
+ print("Concepts params : ", concept_data_args)
34
+ self.concepts = instantiate_from_config(concept_data_args)
35
+ self.concepts.prepare_data()
36
+ self.concepts.setup()
37
+ del args[CONCEPT_DATA_KEY]
38
+
39
+
40
+ super().__init__(**args)
41
+
42
+ if not self.cw_module_infer:
43
+ self.encoder.norm_out = cw_layer(self.encoder.block_in)
44
+ print("Changed to cw layer after loading base VQGAN")
45
+
46
+
47
+ def training_step(self, batch, batch_idx, optimizer_idx):
48
+ if (batch_idx+1)%30==0 and optimizer_idx==0:
49
+ print('cw module')
50
+ self.eval()
51
+ with torch.no_grad():
52
+ for _, concept_batch in enumerate(self.concepts.train_dataloader()):
53
+ for idx, concept in enumerate(concept_batch['class'].unique()):
54
+ concept_index = concept.item()
55
+ self.encoder.norm_out.mode = concept_index
56
+ X_var = concept_batch['image'][concept_batch['class'] == concept]
57
+ X_var = X_var.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format)
58
+ X_var = torch.autograd.Variable(X_var).cuda()
59
+ X_var = X_var.float()
60
+ self(X_var)
61
+ break
62
+
63
+ self.encoder.norm_out.update_rotation_matrix()
64
+
65
+ self.encoder.norm_out.mode = -1
66
+ self.train()
67
+
68
+ # breakpoint()
69
+ x = self.get_input(batch, self.image_key)
70
+ xrec, qloss = self(x, return_pred_indices=False)
71
+
72
+ # if optimizer_idx == 0 or (not self.loss.has_discriminator):
73
+ if optimizer_idx == 0:
74
+ # autoencode
75
+ aeloss, log_dict_ae = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
76
+ last_layer=self.get_last_layer(), split="train")
77
+
78
+ self.log("train/aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
79
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
80
+ return aeloss
81
+
82
+ # if optimizer_idx == 1 and self.loss.has_discriminator:
83
+ if optimizer_idx == 1:
84
+ # discriminator
85
+ discloss, log_dict_disc = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
86
+ last_layer=self.get_last_layer(), split="train")
87
+ self.log("train/discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
88
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True)
89
+ return discloss
90
+
91
+
92
+ @torch.no_grad()
93
+ def test_step(self, batch, batch_idx):
94
+ x = self.get_input(batch, self.image_key)
95
+ h = self.encoder(x)
96
+ h = self.quant_conv(h)
97
+ class_label = batch['class']
98
+
99
+ return {'z_cw': h,
100
+ 'label': class_label,
101
+ 'class_name': batch['class_name']}
102
+
103
+ # NOTE: This is kinda hacky. But ok for now for test purposes.
104
+ def set_test_chkpt_path(self, chkpt_path):
105
+ self.test_chkpt_path = chkpt_path
106
+
107
+ @torch.no_grad()
108
+ def test_epoch_end(self, in_out):
109
+ postfix_name = 'inference_false'
110
+ z_cw =torch.cat([x['z_cw'] for x in in_out], 0)
111
+ labels =torch.cat([x['label'] for x in in_out], 0)
112
+ sorting_indices = np.argsort(labels.cpu())
113
+ sorted_zq_cw = z_cw[sorting_indices, :]
114
+
115
+ classnames = list(itertools.chain.from_iterable([x['class_name'] for x in in_out]))
116
+ sorted_class_names_according_to_class_indx = [classnames[i] for i in sorting_indices]
117
+ z_size = sorted_zq_cw.shape[-1]
118
+ channels = sorted_zq_cw.shape[1]
119
+ # breakpoint()
120
+ figs_folder = os.path.join('/', *self.test_chkpt_path.split('/')[:-2], 'figs/testset_agg')
121
+ if not os.path.exists(figs_folder):
122
+ os.makedirs(figs_folder)
123
+
124
+
125
+
126
+ sorted_zq_cw_aggregated = aggregatefrom_specimen_to_species(sorted_class_names_according_to_class_indx, sorted_zq_cw, z_size, channels)
127
+ z_cosine_distances = get_CosineDistance_matrix(sorted_zq_cw_aggregated)
128
+
129
+ plot_heatmap_at_path(z_cosine_distances.cpu(), figs_folder, self.test_chkpt_path, title=f'Cosine_distances_{postfix_name}', postfix='testset_agg')
130
+
131
+
132
+
133
+ z_cosine_distancess_np = z_cosine_distances.cpu().numpy()
134
+ df = pd.DataFrame(z_cosine_distancess_np)
135
+ df = df.drop(columns=[5, 6])
136
+ df = df.drop([5, 6])
137
+ breakpoint()
138
+ path_to_save = os.path.join(figs_folder, f'CW_z_cosine_distances_{postfix_name}.csv')
139
+ print("saved to path : ", path_to_save)
140
+ df.to_csv(path_to_save)
141
+
142
+ return None
143
+
144
+ class CWmodelInterface(VQModel):
145
+
146
+ def __init__(self, **args):
147
+ print(args)
148
+
149
+ self.save_hyperparameters()
150
+
151
+ concept_data_args = args[CONCEPT_DATA_KEY]
152
+ print("Concepts params : ", concept_data_args)
153
+ self.concepts = instantiate_from_config(concept_data_args)
154
+ self.concepts.prepare_data()
155
+ self.concepts.setup()
156
+ del args[CONCEPT_DATA_KEY]
157
+
158
+
159
+ super().__init__(**args)
160
+
161
+ if not self.cw_module_infer:
162
+ self.encoder.norm_out = cw_layer(self.encoder.block_in)
163
+ print("Changed to cw layer after loading base VQGAN")
164
+
165
+ def encode(self, x):
166
+ h = self.encoder(x)
167
+ h = self.quant_conv(h)
168
+ return h
169
+
170
+ def decode(self, h, force_not_quantize=False):
171
+ # also go through quantization layer
172
+ if not force_not_quantize:
173
+ quant, emb_loss, info = self.quantize(h)
174
+ else:
175
+ quant = h
176
+ quant = self.post_quant_conv(quant)
177
+ dec = self.decoder(quant)
178
+ return dec
179
+
180
+
181
+ class CWmodelKL(AutoencoderKL):
182
+ def __init__(self, **args):
183
+ print(args)
184
+
185
+ self.save_hyperparameters()
186
+
187
+ concept_data_args = args[CONCEPT_DATA_KEY]
188
+ print("Concepts params : ", concept_data_args)
189
+ self.concepts = instantiate_from_config(concept_data_args)
190
+ self.concepts.prepare_data()
191
+ self.concepts.setup()
192
+ del args[CONCEPT_DATA_KEY]
193
+
194
+
195
+ super().__init__(**args)
196
+
197
+ if not self.cw_module_infer:
198
+ self.encoder.norm_out = cw_layer(self.encoder.block_in)
199
+ print("Changed to cw layer after loading base KL Autoecoder")
200
+
201
+
202
+ def training_step(self, batch, batch_idx, optimizer_idx):
203
+ if (batch_idx+1)%30==0 and optimizer_idx==0:
204
+ print('cw module')
205
+ self.eval()
206
+ with torch.no_grad():
207
+ for _, concept_batch in enumerate(self.concepts.train_dataloader()):
208
+ for idx, concept in enumerate(concept_batch['class'].unique()):
209
+ concept_index = concept.item()
210
+ self.encoder.norm_out.mode = concept_index
211
+ X_var = concept_batch['image'][concept_batch['class'] == concept]
212
+ X_var = X_var.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format)
213
+ X_var = torch.autograd.Variable(X_var).cuda()
214
+ X_var = X_var.float()
215
+ self(X_var)
216
+ break
217
+
218
+ self.encoder.norm_out.update_rotation_matrix()
219
+
220
+ self.encoder.norm_out.mode = -1
221
+ self.train()
222
+
223
+ # breakpoint()
224
+ inputs = self.get_input(batch, self.image_key)
225
+ reconstructions, posterior = self(inputs)
226
+
227
+ if optimizer_idx == 0:
228
+ # autoencode
229
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
230
+ last_layer=self.get_last_layer(), split="train")
231
+
232
+ self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
233
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
234
+ return aeloss
235
+
236
+ if optimizer_idx == 1:
237
+ # discriminator
238
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
239
+ last_layer=self.get_last_layer(), split="train")
240
+ self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
241
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
242
+ return discloss
ldm/models/diffusion/__init__.py ADDED
File without changes
ldm/models/diffusion/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (153 Bytes). View file
 
ldm/models/diffusion/__pycache__/ddim.cpython-38.pyc ADDED
Binary file (6.21 kB). View file
 
ldm/models/diffusion/__pycache__/ddpm.cpython-38.pyc ADDED
Binary file (44.2 kB). View file
 
ldm/models/diffusion/__pycache__/plms.cpython-38.pyc ADDED
Binary file (7.36 kB). View file
 
ldm/models/diffusion/classifier.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import pytorch_lightning as pl
4
+ from omegaconf import OmegaConf
5
+ from torch.nn import functional as F
6
+ from torch.optim import AdamW
7
+ from torch.optim.lr_scheduler import LambdaLR
8
+ from copy import deepcopy
9
+ from einops import rearrange
10
+ from glob import glob
11
+ from natsort import natsorted
12
+
13
+ from ldm.modules.diffusionmodules.openaimodel import EncoderUNetModel, UNetModel
14
+ from ldm.util import log_txt_as_img, default, ismap, instantiate_from_config
15
+
16
+ __models__ = {
17
+ 'class_label': EncoderUNetModel,
18
+ 'segmentation': UNetModel
19
+ }
20
+
21
+
22
+ def disabled_train(self, mode=True):
23
+ """Overwrite model.train with this function to make sure train/eval mode
24
+ does not change anymore."""
25
+ return self
26
+
27
+
28
+ class NoisyLatentImageClassifier(pl.LightningModule):
29
+
30
+ def __init__(self,
31
+ diffusion_path,
32
+ num_classes,
33
+ ckpt_path=None,
34
+ pool='attention',
35
+ label_key=None,
36
+ diffusion_ckpt_path=None,
37
+ scheduler_config=None,
38
+ weight_decay=1.e-2,
39
+ log_steps=10,
40
+ monitor='val/loss',
41
+ *args,
42
+ **kwargs):
43
+ super().__init__(*args, **kwargs)
44
+ self.num_classes = num_classes
45
+ # get latest config of diffusion model
46
+ diffusion_config = natsorted(glob(os.path.join(diffusion_path, 'configs', '*-project.yaml')))[-1]
47
+ self.diffusion_config = OmegaConf.load(diffusion_config).model
48
+ self.diffusion_config.params.ckpt_path = diffusion_ckpt_path
49
+ self.load_diffusion()
50
+
51
+ self.monitor = monitor
52
+ self.numd = self.diffusion_model.first_stage_model.encoder.num_resolutions - 1
53
+ self.log_time_interval = self.diffusion_model.num_timesteps // log_steps
54
+ self.log_steps = log_steps
55
+
56
+ self.label_key = label_key if not hasattr(self.diffusion_model, 'cond_stage_key') \
57
+ else self.diffusion_model.cond_stage_key
58
+
59
+ assert self.label_key is not None, 'label_key neither in diffusion model nor in model.params'
60
+
61
+ if self.label_key not in __models__:
62
+ raise NotImplementedError()
63
+
64
+ self.load_classifier(ckpt_path, pool)
65
+
66
+ self.scheduler_config = scheduler_config
67
+ self.use_scheduler = self.scheduler_config is not None
68
+ self.weight_decay = weight_decay
69
+
70
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
71
+ sd = torch.load(path, map_location="cpu")
72
+ if "state_dict" in list(sd.keys()):
73
+ sd = sd["state_dict"]
74
+ keys = list(sd.keys())
75
+ for k in keys:
76
+ for ik in ignore_keys:
77
+ if k.startswith(ik):
78
+ print("Deleting key {} from state_dict.".format(k))
79
+ del sd[k]
80
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
81
+ sd, strict=False)
82
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
83
+ if len(missing) > 0:
84
+ print(f"Missing Keys: {missing}")
85
+ if len(unexpected) > 0:
86
+ print(f"Unexpected Keys: {unexpected}")
87
+
88
+ def load_diffusion(self):
89
+ model = instantiate_from_config(self.diffusion_config)
90
+ self.diffusion_model = model.eval()
91
+ self.diffusion_model.train = disabled_train
92
+ for param in self.diffusion_model.parameters():
93
+ param.requires_grad = False
94
+
95
+ def load_classifier(self, ckpt_path, pool):
96
+ model_config = deepcopy(self.diffusion_config.params.unet_config.params)
97
+ model_config.in_channels = self.diffusion_config.params.unet_config.params.out_channels
98
+ model_config.out_channels = self.num_classes
99
+ if self.label_key == 'class_label':
100
+ model_config.pool = pool
101
+
102
+ self.model = __models__[self.label_key](**model_config)
103
+ if ckpt_path is not None:
104
+ print('#####################################################################')
105
+ print(f'load from ckpt "{ckpt_path}"')
106
+ print('#####################################################################')
107
+ self.init_from_ckpt(ckpt_path)
108
+
109
+ @torch.no_grad()
110
+ def get_x_noisy(self, x, t, noise=None):
111
+ noise = default(noise, lambda: torch.randn_like(x))
112
+ continuous_sqrt_alpha_cumprod = None
113
+ if self.diffusion_model.use_continuous_noise:
114
+ continuous_sqrt_alpha_cumprod = self.diffusion_model.sample_continuous_noise_level(x.shape[0], t + 1)
115
+ # todo: make sure t+1 is correct here
116
+
117
+ return self.diffusion_model.q_sample(x_start=x, t=t, noise=noise,
118
+ continuous_sqrt_alpha_cumprod=continuous_sqrt_alpha_cumprod)
119
+
120
+ def forward(self, x_noisy, t, *args, **kwargs):
121
+ return self.model(x_noisy, t)
122
+
123
+ @torch.no_grad()
124
+ def get_input(self, batch, k):
125
+ x = batch[k]
126
+ if len(x.shape) == 3:
127
+ x = x[..., None]
128
+ x = rearrange(x, 'b h w c -> b c h w')
129
+ x = x.to(memory_format=torch.contiguous_format).float()
130
+ return x
131
+
132
+ @torch.no_grad()
133
+ def get_conditioning(self, batch, k=None):
134
+ if k is None:
135
+ k = self.label_key
136
+ assert k is not None, 'Needs to provide label key'
137
+
138
+ targets = batch[k].to(self.device)
139
+
140
+ if self.label_key == 'segmentation':
141
+ targets = rearrange(targets, 'b h w c -> b c h w')
142
+ for down in range(self.numd):
143
+ h, w = targets.shape[-2:]
144
+ targets = F.interpolate(targets, size=(h // 2, w // 2), mode='nearest')
145
+
146
+ # targets = rearrange(targets,'b c h w -> b h w c')
147
+
148
+ return targets
149
+
150
+ def compute_top_k(self, logits, labels, k, reduction="mean"):
151
+ _, top_ks = torch.topk(logits, k, dim=1)
152
+ if reduction == "mean":
153
+ return (top_ks == labels[:, None]).float().sum(dim=-1).mean().item()
154
+ elif reduction == "none":
155
+ return (top_ks == labels[:, None]).float().sum(dim=-1)
156
+
157
+ def on_train_epoch_start(self):
158
+ # save some memory
159
+ self.diffusion_model.model.to('cpu')
160
+
161
+ @torch.no_grad()
162
+ def write_logs(self, loss, logits, targets):
163
+ log_prefix = 'train' if self.training else 'val'
164
+ log = {}
165
+ log[f"{log_prefix}/loss"] = loss.mean()
166
+ log[f"{log_prefix}/acc@1"] = self.compute_top_k(
167
+ logits, targets, k=1, reduction="mean"
168
+ )
169
+ log[f"{log_prefix}/acc@5"] = self.compute_top_k(
170
+ logits, targets, k=5, reduction="mean"
171
+ )
172
+
173
+ self.log_dict(log, prog_bar=False, logger=True, on_step=self.training, on_epoch=True)
174
+ self.log('loss', log[f"{log_prefix}/loss"], prog_bar=True, logger=False)
175
+ self.log('global_step', self.global_step, logger=False, on_epoch=False, prog_bar=True)
176
+ lr = self.optimizers().param_groups[0]['lr']
177
+ self.log('lr_abs', lr, on_step=True, logger=True, on_epoch=False, prog_bar=True)
178
+
179
+ def shared_step(self, batch, t=None):
180
+ x, *_ = self.diffusion_model.get_input(batch, k=self.diffusion_model.first_stage_key)
181
+ targets = self.get_conditioning(batch)
182
+ if targets.dim() == 4:
183
+ targets = targets.argmax(dim=1)
184
+ if t is None:
185
+ t = torch.randint(0, self.diffusion_model.num_timesteps, (x.shape[0],), device=self.device).long()
186
+ else:
187
+ t = torch.full(size=(x.shape[0],), fill_value=t, device=self.device).long()
188
+ x_noisy = self.get_x_noisy(x, t)
189
+ logits = self(x_noisy, t)
190
+
191
+ loss = F.cross_entropy(logits, targets, reduction='none')
192
+
193
+ self.write_logs(loss.detach(), logits.detach(), targets.detach())
194
+
195
+ loss = loss.mean()
196
+ return loss, logits, x_noisy, targets
197
+
198
+ def training_step(self, batch, batch_idx):
199
+ loss, *_ = self.shared_step(batch)
200
+ return loss
201
+
202
+ def reset_noise_accs(self):
203
+ self.noisy_acc = {t: {'acc@1': [], 'acc@5': []} for t in
204
+ range(0, self.diffusion_model.num_timesteps, self.diffusion_model.log_every_t)}
205
+
206
+ def on_validation_start(self):
207
+ self.reset_noise_accs()
208
+
209
+ @torch.no_grad()
210
+ def validation_step(self, batch, batch_idx):
211
+ loss, *_ = self.shared_step(batch)
212
+
213
+ for t in self.noisy_acc:
214
+ _, logits, _, targets = self.shared_step(batch, t)
215
+ self.noisy_acc[t]['acc@1'].append(self.compute_top_k(logits, targets, k=1, reduction='mean'))
216
+ self.noisy_acc[t]['acc@5'].append(self.compute_top_k(logits, targets, k=5, reduction='mean'))
217
+
218
+ return loss
219
+
220
+ def configure_optimizers(self):
221
+ optimizer = AdamW(self.model.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay)
222
+
223
+ if self.use_scheduler:
224
+ scheduler = instantiate_from_config(self.scheduler_config)
225
+
226
+ print("Setting up LambdaLR scheduler...")
227
+ scheduler = [
228
+ {
229
+ 'scheduler': LambdaLR(optimizer, lr_lambda=scheduler.schedule),
230
+ 'interval': 'step',
231
+ 'frequency': 1
232
+ }]
233
+ return [optimizer], scheduler
234
+
235
+ return optimizer
236
+
237
+ @torch.no_grad()
238
+ def log_images(self, batch, N=8, *args, **kwargs):
239
+ log = dict()
240
+ x = self.get_input(batch, self.diffusion_model.first_stage_key)
241
+ log['inputs'] = x
242
+
243
+ y = self.get_conditioning(batch)
244
+
245
+ if self.label_key == 'class_label':
246
+ y = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
247
+ log['labels'] = y
248
+
249
+ if ismap(y):
250
+ log['labels'] = self.diffusion_model.to_rgb(y)
251
+
252
+ for step in range(self.log_steps):
253
+ current_time = step * self.log_time_interval
254
+
255
+ _, logits, x_noisy, _ = self.shared_step(batch, t=current_time)
256
+
257
+ log[f'inputs@t{current_time}'] = x_noisy
258
+
259
+ pred = F.one_hot(logits.argmax(dim=1), num_classes=self.num_classes)
260
+ pred = rearrange(pred, 'b h w c -> b c h w')
261
+
262
+ log[f'pred@t{current_time}'] = self.diffusion_model.to_rgb(pred)
263
+
264
+ for key in log:
265
+ log[key] = log[key][:N]
266
+
267
+ return log
ldm/models/diffusion/ddim.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+
11
+ class DDIMSampler(object):
12
+ def __init__(self, model, schedule="linear", **kwargs):
13
+ super().__init__()
14
+ self.model = model
15
+ self.ddpm_num_timesteps = model.num_timesteps
16
+ self.schedule = schedule
17
+
18
+ def register_buffer(self, name, attr):
19
+ if type(attr) == torch.Tensor:
20
+ if attr.device != torch.device("cuda"):
21
+ attr = attr.to(torch.device("cuda"))
22
+ setattr(self, name, attr)
23
+
24
+ def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
25
+ self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
26
+ num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
27
+ alphas_cumprod = self.model.alphas_cumprod
28
+ assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
29
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
30
+
31
+ self.register_buffer('betas', to_torch(self.model.betas))
32
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
33
+ self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
34
+
35
+ # calculations for diffusion q(x_t | x_{t-1}) and others
36
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
37
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
38
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
39
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
40
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
41
+
42
+ # ddim sampling parameters
43
+ ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
44
+ ddim_timesteps=self.ddim_timesteps,
45
+ eta=ddim_eta,verbose=verbose)
46
+ self.register_buffer('ddim_sigmas', ddim_sigmas)
47
+ self.register_buffer('ddim_alphas', ddim_alphas)
48
+ self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
49
+ self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
50
+ sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
51
+ (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
52
+ 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
53
+ self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
54
+
55
+ @torch.no_grad()
56
+ def sample(self,
57
+ S,
58
+ batch_size,
59
+ shape,
60
+ conditioning=None,
61
+ callback=None,
62
+ normals_sequence=None,
63
+ img_callback=None,
64
+ quantize_x0=False,
65
+ eta=0.,
66
+ mask=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,
77
+ # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
78
+ **kwargs
79
+ ):
80
+ if conditioning is not None:
81
+ if isinstance(conditioning, dict):
82
+ cbs = conditioning[list(conditioning.keys())[0]].shape[0]
83
+ if cbs != batch_size:
84
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
85
+ else:
86
+ if conditioning.shape[0] != batch_size:
87
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
88
+
89
+ self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
90
+ # sampling
91
+ C, H, W = shape
92
+ size = (batch_size, C, H, W)
93
+ print(f'Data shape for DDIM sampling is {size}, eta {eta}')
94
+
95
+ samples, intermediates = self.ddim_sampling(conditioning, size,
96
+ callback=callback,
97
+ img_callback=img_callback,
98
+ quantize_denoised=quantize_x0,
99
+ mask=mask, x0=x0,
100
+ ddim_use_original_steps=False,
101
+ noise_dropout=noise_dropout,
102
+ temperature=temperature,
103
+ score_corrector=score_corrector,
104
+ corrector_kwargs=corrector_kwargs,
105
+ x_T=x_T,
106
+ log_every_t=log_every_t,
107
+ unconditional_guidance_scale=unconditional_guidance_scale,
108
+ unconditional_conditioning=unconditional_conditioning,
109
+ )
110
+ return samples, intermediates
111
+
112
+ @torch.no_grad()
113
+ def ddim_sampling(self, cond, shape,
114
+ x_T=None, ddim_use_original_steps=False,
115
+ callback=None, timesteps=None, quantize_denoised=False,
116
+ mask=None, x0=None, img_callback=None, log_every_t=100,
117
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
118
+ unconditional_guidance_scale=1., unconditional_conditioning=None,):
119
+ device = self.model.betas.device
120
+ b = shape[0]
121
+ if x_T is None:
122
+ img = torch.randn(shape, device=device)
123
+ else:
124
+ img = x_T
125
+
126
+ if timesteps is None:
127
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
128
+ elif timesteps is not None and not ddim_use_original_steps:
129
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
130
+ timesteps = self.ddim_timesteps[:subset_end]
131
+
132
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
133
+ time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
134
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
135
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
136
+
137
+ iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
138
+
139
+ for i, step in enumerate(iterator):
140
+ index = total_steps - i - 1
141
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
142
+
143
+ if mask is not None:
144
+ assert x0 is not None
145
+ img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
146
+ img = img_orig * mask + (1. - mask) * img
147
+
148
+ outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
149
+ quantize_denoised=quantize_denoised, temperature=temperature,
150
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
151
+ corrector_kwargs=corrector_kwargs,
152
+ unconditional_guidance_scale=unconditional_guidance_scale,
153
+ unconditional_conditioning=unconditional_conditioning)
154
+ img, pred_x0 = outs
155
+ if callback: callback(i)
156
+ if img_callback: img_callback(pred_x0, i)
157
+
158
+ if index % log_every_t == 0 or index == total_steps - 1:
159
+ intermediates['x_inter'].append(img)
160
+ intermediates['pred_x0'].append(pred_x0)
161
+
162
+ return img, intermediates
163
+
164
+ @torch.no_grad()
165
+ def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
166
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
167
+ unconditional_guidance_scale=1., unconditional_conditioning=None):
168
+ b, *_, device = *x.shape, x.device
169
+
170
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
171
+ e_t = self.model.apply_model(x, t, c)
172
+ else:
173
+ x_in = torch.cat([x] * 2)
174
+ t_in = torch.cat([t] * 2)
175
+ c_in = torch.cat([unconditional_conditioning, c])
176
+ e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
177
+ e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
178
+
179
+ if score_corrector is not None:
180
+ assert self.model.parameterization == "eps"
181
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
182
+
183
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
184
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
185
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
186
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
187
+ # select parameters corresponding to the currently considered timestep
188
+ a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
189
+ a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
190
+ sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
191
+ sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
192
+
193
+ # current prediction for x_0
194
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
195
+ if quantize_denoised:
196
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
197
+ # direction pointing to x_t
198
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
199
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
200
+ if noise_dropout > 0.:
201
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
202
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
203
+ return x_prev, pred_x0
ldm/models/diffusion/ddpm.py ADDED
@@ -0,0 +1,1451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
16
+ from functools import partial
17
+ from tqdm import tqdm
18
+ from torchvision.utils import make_grid
19
+ from pytorch_lightning.utilities.distributed import rank_zero_only
20
+
21
+ from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
22
+ from ldm.modules.ema import LitEma
23
+ from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
24
+ from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL
25
+ from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
26
+ from ldm.models.diffusion.ddim import DDIMSampler
27
+
28
+
29
+ __conditioning_keys__ = {'concat': 'c_concat',
30
+ 'crossattn': 'c_crossattn',
31
+ 'adm': 'y'}
32
+
33
+
34
+ def disabled_train(self, mode=True):
35
+ """Overwrite model.train with this function to make sure train/eval mode
36
+ does not change anymore."""
37
+ return self
38
+
39
+
40
+ def uniform_on_device(r1, r2, shape, device):
41
+ return (r1 - r2) * torch.rand(*shape, device=device) + r2
42
+
43
+
44
+ class DDPM(pl.LightningModule):
45
+ # classic DDPM with Gaussian diffusion, in image space
46
+ def __init__(self,
47
+ unet_config,
48
+ timesteps=1000,
49
+ beta_schedule="linear",
50
+ loss_type="l2",
51
+ ckpt_path=None,
52
+ ignore_keys=[],
53
+ load_only_unet=False,
54
+ monitor="val/loss",
55
+ use_ema=True,
56
+ first_stage_key="image",
57
+ image_size=256,
58
+ channels=3,
59
+ log_every_t=100,
60
+ clip_denoised=True,
61
+ linear_start=1e-4,
62
+ linear_end=2e-2,
63
+ cosine_s=8e-3,
64
+ given_betas=None,
65
+ original_elbo_weight=0.,
66
+ v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
67
+ l_simple_weight=1.,
68
+ conditioning_key=None,
69
+ parameterization="eps", # all assuming fixed variance schedules
70
+ scheduler_config=None,
71
+ use_positional_encodings=False,
72
+ learn_logvar=False,
73
+ logvar_init=0.,
74
+ ):
75
+ super().__init__()
76
+ assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
77
+ self.parameterization = parameterization
78
+ print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
79
+ self.cond_stage_model = None
80
+ self.clip_denoised = clip_denoised
81
+ self.log_every_t = log_every_t
82
+ self.first_stage_key = first_stage_key
83
+ self.image_size = image_size # try conv?
84
+ self.channels = channels
85
+ self.use_positional_encodings = use_positional_encodings
86
+ self.model = DiffusionWrapper(unet_config, conditioning_key)
87
+ count_params(self.model, verbose=True)
88
+ self.use_ema = use_ema
89
+ if self.use_ema:
90
+ self.model_ema = LitEma(self.model)
91
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
92
+
93
+ self.use_scheduler = scheduler_config is not None
94
+ if self.use_scheduler:
95
+ self.scheduler_config = scheduler_config
96
+
97
+ self.v_posterior = v_posterior
98
+ self.original_elbo_weight = original_elbo_weight
99
+ self.l_simple_weight = l_simple_weight
100
+
101
+ if monitor is not None:
102
+ self.monitor = monitor
103
+ if ckpt_path is not None:
104
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
105
+
106
+ self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
107
+ linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
108
+
109
+ self.loss_type = loss_type
110
+
111
+ self.learn_logvar = learn_logvar
112
+ self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
113
+ if self.learn_logvar:
114
+ self.logvar = nn.Parameter(self.logvar, requires_grad=True)
115
+
116
+
117
+ def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
118
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
119
+ if exists(given_betas):
120
+ betas = given_betas
121
+ else:
122
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
123
+ cosine_s=cosine_s)
124
+ alphas = 1. - betas
125
+ alphas_cumprod = np.cumprod(alphas, axis=0)
126
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
127
+
128
+ timesteps, = betas.shape
129
+ self.num_timesteps = int(timesteps)
130
+ self.linear_start = linear_start
131
+ self.linear_end = linear_end
132
+ assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
133
+
134
+ to_torch = partial(torch.tensor, dtype=torch.float32)
135
+
136
+ self.register_buffer('betas', to_torch(betas))
137
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
138
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
139
+
140
+ # calculations for diffusion q(x_t | x_{t-1}) and others
141
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
142
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
143
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
144
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
145
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
146
+
147
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
148
+ posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
149
+ 1. - alphas_cumprod) + self.v_posterior * betas
150
+ # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
151
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
152
+ # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
153
+ self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
154
+ self.register_buffer('posterior_mean_coef1', to_torch(
155
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
156
+ self.register_buffer('posterior_mean_coef2', to_torch(
157
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
158
+
159
+ if self.parameterization == "eps":
160
+ lvlb_weights = self.betas ** 2 / (
161
+ 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
162
+ elif self.parameterization == "x0":
163
+ lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
164
+ else:
165
+ raise NotImplementedError("mu not supported")
166
+ # TODO how to choose this term
167
+ lvlb_weights[0] = lvlb_weights[1]
168
+ self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
169
+ assert not torch.isnan(self.lvlb_weights).all()
170
+
171
+ @contextmanager
172
+ def ema_scope(self, context=None):
173
+ if self.use_ema:
174
+ self.model_ema.store(self.model.parameters())
175
+ self.model_ema.copy_to(self.model)
176
+ if context is not None:
177
+ print(f"{context}: Switched to EMA weights")
178
+ try:
179
+ yield None
180
+ finally:
181
+ if self.use_ema:
182
+ self.model_ema.restore(self.model.parameters())
183
+ if context is not None:
184
+ print(f"{context}: Restored training weights")
185
+
186
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
187
+ sd = torch.load(path, map_location="cpu")
188
+ if "state_dict" in list(sd.keys()):
189
+ sd = sd["state_dict"]
190
+ keys = list(sd.keys())
191
+ for k in keys:
192
+ for ik in ignore_keys:
193
+ if k.startswith(ik):
194
+ print("Deleting key {} from state_dict.".format(k))
195
+ del sd[k]
196
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
197
+ sd, strict=False)
198
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
199
+ if len(missing) > 0:
200
+ print(f"Missing Keys: {missing}")
201
+ if len(unexpected) > 0:
202
+ print(f"Unexpected Keys: {unexpected}")
203
+
204
+ def q_mean_variance(self, x_start, t):
205
+ """
206
+ Get the distribution q(x_t | x_0).
207
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
208
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
209
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
210
+ """
211
+ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
212
+ variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
213
+ log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
214
+ return mean, variance, log_variance
215
+
216
+ def predict_start_from_noise(self, x_t, t, noise):
217
+ return (
218
+ extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
219
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
220
+ )
221
+
222
+ def q_posterior(self, x_start, x_t, t):
223
+ posterior_mean = (
224
+ extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
225
+ extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
226
+ )
227
+ posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
228
+ posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
229
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
230
+
231
+ def p_mean_variance(self, x, t, clip_denoised: bool):
232
+ model_out = self.model(x, t)
233
+ if self.parameterization == "eps":
234
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
235
+ elif self.parameterization == "x0":
236
+ x_recon = model_out
237
+ if clip_denoised:
238
+ x_recon.clamp_(-1., 1.)
239
+
240
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
241
+ return model_mean, posterior_variance, posterior_log_variance
242
+
243
+ @torch.no_grad()
244
+ def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
245
+ b, *_, device = *x.shape, x.device
246
+ model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
247
+ noise = noise_like(x.shape, device, repeat_noise)
248
+ # no noise when t == 0
249
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
250
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
251
+
252
+ @torch.no_grad()
253
+ def p_sample_loop(self, shape, return_intermediates=False):
254
+ device = self.betas.device
255
+ b = shape[0]
256
+ img = torch.randn(shape, device=device)
257
+ intermediates = [img]
258
+ for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
259
+ img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
260
+ clip_denoised=self.clip_denoised)
261
+ if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
262
+ intermediates.append(img)
263
+ if return_intermediates:
264
+ return img, intermediates
265
+ return img
266
+
267
+ @torch.no_grad()
268
+ def sample(self, batch_size=16, return_intermediates=False):
269
+ image_size = self.image_size
270
+ channels = self.channels
271
+ return self.p_sample_loop((batch_size, channels, image_size, image_size),
272
+ return_intermediates=return_intermediates)
273
+
274
+ def q_sample(self, x_start, t, noise=None):
275
+ noise = default(noise, lambda: torch.randn_like(x_start))
276
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
277
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
278
+
279
+ def get_loss(self, pred, target, mean=True):
280
+ if self.loss_type == 'l1':
281
+ loss = (target - pred).abs()
282
+ if mean:
283
+ loss = loss.mean()
284
+ elif self.loss_type == 'l2':
285
+ if mean:
286
+ loss = torch.nn.functional.mse_loss(target, pred)
287
+ else:
288
+ loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
289
+ else:
290
+ raise NotImplementedError("unknown loss type '{loss_type}'")
291
+
292
+ return loss
293
+
294
+ def p_losses(self, x_start, t, noise=None):
295
+ noise = default(noise, lambda: torch.randn_like(x_start))
296
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
297
+ model_out = self.model(x_noisy, t)
298
+
299
+ loss_dict = {}
300
+ if self.parameterization == "eps":
301
+ target = noise
302
+ elif self.parameterization == "x0":
303
+ target = x_start
304
+ else:
305
+ raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported")
306
+
307
+ loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
308
+
309
+ log_prefix = 'train' if self.training else 'val'
310
+
311
+ loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
312
+ loss_simple = loss.mean() * self.l_simple_weight
313
+
314
+ loss_vlb = (self.lvlb_weights[t] * loss).mean()
315
+ loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
316
+
317
+ loss = loss_simple + self.original_elbo_weight * loss_vlb
318
+
319
+ loss_dict.update({f'{log_prefix}/loss': loss})
320
+
321
+ return loss, loss_dict
322
+
323
+ def forward(self, x, *args, **kwargs):
324
+ # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
325
+ # assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
326
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
327
+ return self.p_losses(x, t, *args, **kwargs)
328
+
329
+ def get_input(self, batch, k):
330
+ x = batch[k]
331
+ if len(x.shape) == 3:
332
+ x = x[..., None]
333
+ x = rearrange(x, 'b h w c -> b c h w')
334
+ x = x.to(memory_format=torch.contiguous_format).float()
335
+ return x
336
+
337
+ def shared_step(self, batch):
338
+ x = self.get_input(batch, self.first_stage_key)
339
+ loss, loss_dict = self(x)
340
+ return loss, loss_dict
341
+
342
+ def training_step(self, batch, batch_idx):
343
+ loss, loss_dict = self.shared_step(batch)
344
+
345
+ self.log_dict(loss_dict, prog_bar=True,
346
+ logger=True, on_step=True, on_epoch=True)
347
+
348
+ self.log("global_step", self.global_step,
349
+ prog_bar=True, logger=True, on_step=True, on_epoch=False)
350
+
351
+ if self.use_scheduler:
352
+ lr = self.optimizers().param_groups[0]['lr']
353
+ self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
354
+
355
+ return loss
356
+
357
+ @torch.no_grad()
358
+ def validation_step(self, batch, batch_idx):
359
+ _, loss_dict_no_ema = self.shared_step(batch)
360
+ with self.ema_scope():
361
+ _, loss_dict_ema = self.shared_step(batch)
362
+ loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
363
+ self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
364
+ self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
365
+
366
+ def on_train_batch_end(self, *args, **kwargs):
367
+ if self.use_ema:
368
+ self.model_ema(self.model)
369
+
370
+ def _get_rows_from_list(self, samples):
371
+ n_imgs_per_row = len(samples)
372
+ denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
373
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
374
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
375
+ return denoise_grid
376
+
377
+ @torch.no_grad()
378
+ def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
379
+ log = dict()
380
+ x = self.get_input(batch, self.first_stage_key)
381
+ N = min(x.shape[0], N)
382
+ n_row = min(x.shape[0], n_row)
383
+ x = x.to(self.device)[:N]
384
+ log["inputs"] = x
385
+
386
+ # get diffusion row
387
+ diffusion_row = list()
388
+ x_start = x[:n_row]
389
+
390
+ for t in range(self.num_timesteps):
391
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
392
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
393
+ t = t.to(self.device).long()
394
+ noise = torch.randn_like(x_start)
395
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
396
+ diffusion_row.append(x_noisy)
397
+
398
+ log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
399
+
400
+ if sample:
401
+ # get denoise row
402
+ with self.ema_scope("Plotting"):
403
+ samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
404
+
405
+ log["samples"] = samples
406
+ log["denoise_row"] = self._get_rows_from_list(denoise_row)
407
+
408
+ if return_keys:
409
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
410
+ return log
411
+ else:
412
+ return {key: log[key] for key in return_keys}
413
+ return log
414
+
415
+ def configure_optimizers(self):
416
+ lr = self.learning_rate
417
+ params = list(self.model.parameters())
418
+ if self.learn_logvar:
419
+ params = params + [self.logvar]
420
+ opt = torch.optim.AdamW(params, lr=lr)
421
+ return opt
422
+
423
+
424
+ class LatentDiffusion(DDPM):
425
+ """main class"""
426
+ def __init__(self,
427
+ first_stage_config,
428
+ cond_stage_config,
429
+ num_timesteps_cond=None,
430
+ cond_stage_key="image",
431
+ cond_stage_trainable=False,
432
+ concat_mode=True,
433
+ cond_stage_forward=None,
434
+ conditioning_key=None,
435
+ scale_factor=1.0,
436
+ scale_by_std=False,
437
+ *args, **kwargs):
438
+ self.num_timesteps_cond = default(num_timesteps_cond, 1)
439
+ self.scale_by_std = scale_by_std
440
+ assert self.num_timesteps_cond <= kwargs['timesteps']
441
+ # for backwards compatibility after implementation of DiffusionWrapper
442
+ if conditioning_key is None:
443
+ conditioning_key = 'concat' if concat_mode else 'crossattn'
444
+ if cond_stage_config == '__is_unconditional__':
445
+ conditioning_key = None
446
+ ckpt_path = kwargs.pop("ckpt_path", None)
447
+ ignore_keys = kwargs.pop("ignore_keys", [])
448
+ super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
449
+ self.concat_mode = concat_mode
450
+ self.cond_stage_trainable = cond_stage_trainable
451
+ self.cond_stage_key = cond_stage_key
452
+ try:
453
+ self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
454
+ except:
455
+ self.num_downs = 0
456
+ if not scale_by_std:
457
+ self.scale_factor = scale_factor
458
+ else:
459
+ self.register_buffer('scale_factor', torch.tensor(scale_factor))
460
+ self.instantiate_first_stage(first_stage_config)
461
+ self.instantiate_cond_stage(cond_stage_config)
462
+ self.cond_stage_forward = cond_stage_forward
463
+ self.clip_denoised = False
464
+ self.bbox_tokenizer = None
465
+
466
+ self.restarted_from_ckpt = False
467
+ if ckpt_path is not None:
468
+ self.init_from_ckpt(ckpt_path, ignore_keys)
469
+ self.restarted_from_ckpt = True
470
+
471
+ def make_cond_schedule(self, ):
472
+ self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
473
+ ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
474
+ self.cond_ids[:self.num_timesteps_cond] = ids
475
+
476
+ @rank_zero_only
477
+ @torch.no_grad()
478
+ def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
479
+ # only for very first batch
480
+ 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:
481
+ assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
482
+ # set rescale weight to 1./std of encodings
483
+ print("### USING STD-RESCALING ###")
484
+ x = super().get_input(batch, self.first_stage_key)
485
+ x = x.to(self.device)
486
+ encoder_posterior = self.encode_first_stage(x)
487
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
488
+ del self.scale_factor
489
+ self.register_buffer('scale_factor', 1. / z.flatten().std())
490
+ print(f"setting self.scale_factor to {self.scale_factor}")
491
+ print("### USING STD-RESCALING ###")
492
+
493
+ def register_schedule(self,
494
+ given_betas=None, beta_schedule="linear", timesteps=1000,
495
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
496
+ super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
497
+
498
+ self.shorten_cond_schedule = self.num_timesteps_cond > 1
499
+ if self.shorten_cond_schedule:
500
+ self.make_cond_schedule()
501
+
502
+ def instantiate_first_stage(self, config):
503
+ model = instantiate_from_config(config)
504
+ self.first_stage_model = model.eval()
505
+ self.first_stage_model.train = disabled_train
506
+ for param in self.first_stage_model.parameters():
507
+ param.requires_grad = False
508
+
509
+ def instantiate_cond_stage(self, config):
510
+ if not self.cond_stage_trainable:
511
+ if config == "__is_first_stage__":
512
+ print("Using first stage also as cond stage.")
513
+ self.cond_stage_model = self.first_stage_model
514
+ elif config == "__is_unconditional__":
515
+ print(f"Training {self.__class__.__name__} as an unconditional model.")
516
+ self.cond_stage_model = None
517
+ # self.be_unconditional = True
518
+ else:
519
+ model = instantiate_from_config(config)
520
+ self.cond_stage_model = model.eval()
521
+ self.cond_stage_model.train = disabled_train
522
+ for param in self.cond_stage_model.parameters():
523
+ param.requires_grad = False
524
+ else:
525
+ assert config != '__is_first_stage__'
526
+ assert config != '__is_unconditional__'
527
+ model = instantiate_from_config(config)
528
+ self.cond_stage_model = model
529
+
530
+ def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
531
+ denoise_row = []
532
+ for zd in tqdm(samples, desc=desc):
533
+ denoise_row.append(self.decode_first_stage(zd.to(self.device),
534
+ force_not_quantize=force_no_decoder_quantization))
535
+ n_imgs_per_row = len(denoise_row)
536
+ denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
537
+ denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
538
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
539
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
540
+ return denoise_grid
541
+
542
+ def get_first_stage_encoding(self, encoder_posterior):
543
+ if isinstance(encoder_posterior, DiagonalGaussianDistribution):
544
+ z = encoder_posterior.sample()
545
+ elif isinstance(encoder_posterior, torch.Tensor):
546
+ z = encoder_posterior
547
+ else:
548
+ raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
549
+ return self.scale_factor * z
550
+
551
+ def get_learned_conditioning(self, c):
552
+ if self.cond_stage_forward is None:
553
+ if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
554
+ c = self.cond_stage_model.encode(c)
555
+ if isinstance(c, DiagonalGaussianDistribution):
556
+ c = c.mode()
557
+ else:
558
+ c = self.cond_stage_model(c)
559
+ else:
560
+ assert hasattr(self.cond_stage_model, self.cond_stage_forward)
561
+ c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
562
+ return c
563
+
564
+ def meshgrid(self, h, w):
565
+ y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
566
+ x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
567
+
568
+ arr = torch.cat([y, x], dim=-1)
569
+ return arr
570
+
571
+ def delta_border(self, h, w):
572
+ """
573
+ :param h: height
574
+ :param w: width
575
+ :return: normalized distance to image border,
576
+ wtith min distance = 0 at border and max dist = 0.5 at image center
577
+ """
578
+ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
579
+ arr = self.meshgrid(h, w) / lower_right_corner
580
+ dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
581
+ dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
582
+ edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
583
+ return edge_dist
584
+
585
+ def get_weighting(self, h, w, Ly, Lx, device):
586
+ weighting = self.delta_border(h, w)
587
+ weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
588
+ self.split_input_params["clip_max_weight"], )
589
+ weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
590
+
591
+ if self.split_input_params["tie_braker"]:
592
+ L_weighting = self.delta_border(Ly, Lx)
593
+ L_weighting = torch.clip(L_weighting,
594
+ self.split_input_params["clip_min_tie_weight"],
595
+ self.split_input_params["clip_max_tie_weight"])
596
+
597
+ L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
598
+ weighting = weighting * L_weighting
599
+ return weighting
600
+
601
+ def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
602
+ """
603
+ :param x: img of size (bs, c, h, w)
604
+ :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
605
+ """
606
+ bs, nc, h, w = x.shape
607
+
608
+ # number of crops in image
609
+ Ly = (h - kernel_size[0]) // stride[0] + 1
610
+ Lx = (w - kernel_size[1]) // stride[1] + 1
611
+
612
+ if uf == 1 and df == 1:
613
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
614
+ unfold = torch.nn.Unfold(**fold_params)
615
+
616
+ fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
617
+
618
+ weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
619
+ normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
620
+ weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
621
+
622
+ elif uf > 1 and df == 1:
623
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
624
+ unfold = torch.nn.Unfold(**fold_params)
625
+
626
+ fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
627
+ dilation=1, padding=0,
628
+ stride=(stride[0] * uf, stride[1] * uf))
629
+ fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
630
+
631
+ weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
632
+ normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
633
+ weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
634
+
635
+ elif df > 1 and uf == 1:
636
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
637
+ unfold = torch.nn.Unfold(**fold_params)
638
+
639
+ fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
640
+ dilation=1, padding=0,
641
+ stride=(stride[0] // df, stride[1] // df))
642
+ fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
643
+
644
+ weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
645
+ normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
646
+ weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
647
+
648
+ else:
649
+ raise NotImplementedError
650
+
651
+ return fold, unfold, normalization, weighting
652
+
653
+ @torch.no_grad()
654
+ def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
655
+ cond_key=None, return_original_cond=False, bs=None):
656
+ x = super().get_input(batch, k)
657
+ if bs is not None:
658
+ x = x[:bs]
659
+ x = x.to(self.device)
660
+ encoder_posterior = self.encode_first_stage(x)
661
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
662
+
663
+ if self.model.conditioning_key is not None:
664
+ if cond_key is None:
665
+ cond_key = self.cond_stage_key
666
+ if cond_key != self.first_stage_key:
667
+ if cond_key in ['caption', 'coordinates_bbox', 'class_name', 'class_to_node']:
668
+ xc = batch[cond_key]
669
+ elif cond_key == 'class_label':
670
+ xc = batch
671
+ else:
672
+ xc = super().get_input(batch, cond_key).to(self.device)
673
+ else:
674
+ xc = x
675
+ if not self.cond_stage_trainable or force_c_encode:
676
+ if isinstance(xc, dict) or isinstance(xc, list):
677
+ # import pudb; pudb.set_trace()
678
+ c = self.get_learned_conditioning(xc)
679
+ else:
680
+ c = self.get_learned_conditioning(xc.to(self.device))
681
+ else:
682
+ c = xc
683
+ if bs is not None:
684
+ c = c[:bs]
685
+
686
+ if self.use_positional_encodings:
687
+ pos_x, pos_y = self.compute_latent_shifts(batch)
688
+ ckey = __conditioning_keys__[self.model.conditioning_key]
689
+ c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
690
+
691
+ else:
692
+ c = None
693
+ xc = None
694
+ if self.use_positional_encodings:
695
+ pos_x, pos_y = self.compute_latent_shifts(batch)
696
+ c = {'pos_x': pos_x, 'pos_y': pos_y}
697
+ out = [z, c]
698
+ if return_first_stage_outputs:
699
+ xrec = self.decode_first_stage(z)
700
+ out.extend([x, xrec])
701
+ if return_original_cond:
702
+ out.append(xc)
703
+ return out
704
+
705
+ @torch.no_grad()
706
+ def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
707
+ if predict_cids:
708
+ if z.dim() == 4:
709
+ z = torch.argmax(z.exp(), dim=1).long()
710
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
711
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
712
+
713
+ z = 1. / self.scale_factor * z
714
+
715
+ if hasattr(self, "split_input_params"):
716
+ if self.split_input_params["patch_distributed_vq"]:
717
+ ks = self.split_input_params["ks"] # eg. (128, 128)
718
+ stride = self.split_input_params["stride"] # eg. (64, 64)
719
+ uf = self.split_input_params["vqf"]
720
+ bs, nc, h, w = z.shape
721
+ if ks[0] > h or ks[1] > w:
722
+ ks = (min(ks[0], h), min(ks[1], w))
723
+ print("reducing Kernel")
724
+
725
+ if stride[0] > h or stride[1] > w:
726
+ stride = (min(stride[0], h), min(stride[1], w))
727
+ print("reducing stride")
728
+
729
+ fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
730
+
731
+ z = unfold(z) # (bn, nc * prod(**ks), L)
732
+ # 1. Reshape to img shape
733
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
734
+
735
+ # 2. apply model loop over last dim
736
+ if isinstance(self.first_stage_model, VQModelInterface):
737
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
738
+ force_not_quantize=predict_cids or force_not_quantize)
739
+ for i in range(z.shape[-1])]
740
+ else:
741
+
742
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
743
+ for i in range(z.shape[-1])]
744
+
745
+ o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
746
+ o = o * weighting
747
+ # Reverse 1. reshape to img shape
748
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
749
+ # stitch crops together
750
+ decoded = fold(o)
751
+ decoded = decoded / normalization # norm is shape (1, 1, h, w)
752
+ return decoded
753
+ else:
754
+ if isinstance(self.first_stage_model, VQModelInterface):
755
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
756
+ else:
757
+ return self.first_stage_model.decode(z)
758
+
759
+ else:
760
+ if isinstance(self.first_stage_model, VQModelInterface):
761
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
762
+ else:
763
+ return self.first_stage_model.decode(z)
764
+
765
+ # same as above but without decorator
766
+ def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
767
+ if predict_cids:
768
+ if z.dim() == 4:
769
+ z = torch.argmax(z.exp(), dim=1).long()
770
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
771
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
772
+
773
+ z = 1. / self.scale_factor * z
774
+
775
+ if hasattr(self, "split_input_params"):
776
+ if self.split_input_params["patch_distributed_vq"]:
777
+ ks = self.split_input_params["ks"] # eg. (128, 128)
778
+ stride = self.split_input_params["stride"] # eg. (64, 64)
779
+ uf = self.split_input_params["vqf"]
780
+ bs, nc, h, w = z.shape
781
+ if ks[0] > h or ks[1] > w:
782
+ ks = (min(ks[0], h), min(ks[1], w))
783
+ print("reducing Kernel")
784
+
785
+ if stride[0] > h or stride[1] > w:
786
+ stride = (min(stride[0], h), min(stride[1], w))
787
+ print("reducing stride")
788
+
789
+ fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
790
+
791
+ z = unfold(z) # (bn, nc * prod(**ks), L)
792
+ # 1. Reshape to img shape
793
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
794
+
795
+ # 2. apply model loop over last dim
796
+ if isinstance(self.first_stage_model, VQModelInterface):
797
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
798
+ force_not_quantize=predict_cids or force_not_quantize)
799
+ for i in range(z.shape[-1])]
800
+ else:
801
+
802
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
803
+ for i in range(z.shape[-1])]
804
+
805
+ o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
806
+ o = o * weighting
807
+ # Reverse 1. reshape to img shape
808
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
809
+ # stitch crops together
810
+ decoded = fold(o)
811
+ decoded = decoded / normalization # norm is shape (1, 1, h, w)
812
+ return decoded
813
+ else:
814
+ if isinstance(self.first_stage_model, VQModelInterface):
815
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
816
+ else:
817
+ return self.first_stage_model.decode(z)
818
+
819
+ else:
820
+ if isinstance(self.first_stage_model, VQModelInterface):
821
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
822
+ else:
823
+ return self.first_stage_model.decode(z)
824
+
825
+ @torch.no_grad()
826
+ def encode_first_stage(self, x):
827
+ if hasattr(self, "split_input_params"):
828
+ if self.split_input_params["patch_distributed_vq"]:
829
+ ks = self.split_input_params["ks"] # eg. (128, 128)
830
+ stride = self.split_input_params["stride"] # eg. (64, 64)
831
+ df = self.split_input_params["vqf"]
832
+ self.split_input_params['original_image_size'] = x.shape[-2:]
833
+ bs, nc, h, w = x.shape
834
+ if ks[0] > h or ks[1] > w:
835
+ ks = (min(ks[0], h), min(ks[1], w))
836
+ print("reducing Kernel")
837
+
838
+ if stride[0] > h or stride[1] > w:
839
+ stride = (min(stride[0], h), min(stride[1], w))
840
+ print("reducing stride")
841
+
842
+ fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df)
843
+ z = unfold(x) # (bn, nc * prod(**ks), L)
844
+ # Reshape to img shape
845
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
846
+
847
+ output_list = [self.first_stage_model.encode(z[:, :, :, :, i])
848
+ for i in range(z.shape[-1])]
849
+
850
+ o = torch.stack(output_list, axis=-1)
851
+ o = o * weighting
852
+
853
+ # Reverse reshape to img shape
854
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
855
+ # stitch crops together
856
+ decoded = fold(o)
857
+ decoded = decoded / normalization
858
+ return decoded
859
+
860
+ else:
861
+ return self.first_stage_model.encode(x)
862
+ else:
863
+ return self.first_stage_model.encode(x)
864
+
865
+ def shared_step(self, batch, **kwargs):
866
+ x, c = self.get_input(batch, self.first_stage_key)
867
+ loss = self(x, c)
868
+ return loss
869
+
870
+ def forward(self, x, c, *args, **kwargs):
871
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
872
+ if self.model.conditioning_key is not None:
873
+ assert c is not None
874
+ if self.cond_stage_trainable:
875
+ c = self.get_learned_conditioning(c)
876
+ if self.shorten_cond_schedule: # TODO: drop this option
877
+ tc = self.cond_ids[t].to(self.device)
878
+ c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
879
+ return self.p_losses(x, c, t, *args, **kwargs)
880
+
881
+ def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset
882
+ def rescale_bbox(bbox):
883
+ x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2])
884
+ y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3])
885
+ w = min(bbox[2] / crop_coordinates[2], 1 - x0)
886
+ h = min(bbox[3] / crop_coordinates[3], 1 - y0)
887
+ return x0, y0, w, h
888
+
889
+ return [rescale_bbox(b) for b in bboxes]
890
+
891
+ def apply_model(self, x_noisy, t, cond, return_ids=False):
892
+
893
+ if isinstance(cond, dict):
894
+ # hybrid case, cond is exptected to be a dict
895
+ pass
896
+ else:
897
+ if not isinstance(cond, list):
898
+ cond = [cond]
899
+ key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
900
+ cond = {key: cond}
901
+
902
+ if hasattr(self, "split_input_params"):
903
+ assert len(cond) == 1 # todo can only deal with one conditioning atm
904
+ assert not return_ids
905
+ ks = self.split_input_params["ks"] # eg. (128, 128)
906
+ stride = self.split_input_params["stride"] # eg. (64, 64)
907
+
908
+ h, w = x_noisy.shape[-2:]
909
+
910
+ fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride)
911
+
912
+ z = unfold(x_noisy) # (bn, nc * prod(**ks), L)
913
+ # Reshape to img shape
914
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
915
+ z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]
916
+
917
+ if self.cond_stage_key in ["image", "LR_image", "segmentation",
918
+ 'bbox_img'] and self.model.conditioning_key: # todo check for completeness
919
+ c_key = next(iter(cond.keys())) # get key
920
+ c = next(iter(cond.values())) # get value
921
+ assert (len(c) == 1) # todo extend to list with more than one elem
922
+ c = c[0] # get element
923
+
924
+ c = unfold(c)
925
+ c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L )
926
+
927
+ cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
928
+
929
+ elif self.cond_stage_key == 'coordinates_bbox':
930
+ assert 'original_image_size' in self.split_input_params, 'BoudingBoxRescaling is missing original_image_size'
931
+
932
+ # assuming padding of unfold is always 0 and its dilation is always 1
933
+ n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
934
+ full_img_h, full_img_w = self.split_input_params['original_image_size']
935
+ # as we are operating on latents, we need the factor from the original image size to the
936
+ # spatial latent size to properly rescale the crops for regenerating the bbox annotations
937
+ num_downs = self.first_stage_model.encoder.num_resolutions - 1
938
+ rescale_latent = 2 ** (num_downs)
939
+
940
+ # get top left postions of patches as conforming for the bbbox tokenizer, therefore we
941
+ # need to rescale the tl patch coordinates to be in between (0,1)
942
+ tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
943
+ rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
944
+ for patch_nr in range(z.shape[-1])]
945
+
946
+ # patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)
947
+ patch_limits = [(x_tl, y_tl,
948
+ rescale_latent * ks[0] / full_img_w,
949
+ rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates]
950
+ # patch_values = [(np.arange(x_tl,min(x_tl+ks, 1.)),np.arange(y_tl,min(y_tl+ks, 1.))) for x_tl, y_tl in tl_patch_coordinates]
951
+
952
+ # tokenize crop coordinates for the bounding boxes of the respective patches
953
+ patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device)
954
+ for bbox in patch_limits] # list of length l with tensors of shape (1, 2)
955
+ print(patch_limits_tknzd[0].shape)
956
+ # cut tknzd crop position from conditioning
957
+ assert isinstance(cond, dict), 'cond must be dict to be fed into model'
958
+ cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device)
959
+ print(cut_cond.shape)
960
+
961
+ adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd])
962
+ adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n')
963
+ print(adapted_cond.shape)
964
+ adapted_cond = self.get_learned_conditioning(adapted_cond)
965
+ print(adapted_cond.shape)
966
+ adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1])
967
+ print(adapted_cond.shape)
968
+
969
+ cond_list = [{'c_crossattn': [e]} for e in adapted_cond]
970
+
971
+ else:
972
+ cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient
973
+
974
+ # apply model by loop over crops
975
+ output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])]
976
+ assert not isinstance(output_list[0],
977
+ tuple) # todo cant deal with multiple model outputs check this never happens
978
+
979
+ o = torch.stack(output_list, axis=-1)
980
+ o = o * weighting
981
+ # Reverse reshape to img shape
982
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
983
+ # stitch crops together
984
+ x_recon = fold(o) / normalization
985
+
986
+ else:
987
+ x_recon = self.model(x_noisy, t, **cond)
988
+
989
+ if isinstance(x_recon, tuple) and not return_ids:
990
+ return x_recon[0]
991
+ else:
992
+ return x_recon
993
+
994
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
995
+ return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
996
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
997
+
998
+ def _prior_bpd(self, x_start):
999
+ """
1000
+ Get the prior KL term for the variational lower-bound, measured in
1001
+ bits-per-dim.
1002
+ This term can't be optimized, as it only depends on the encoder.
1003
+ :param x_start: the [N x C x ...] tensor of inputs.
1004
+ :return: a batch of [N] KL values (in bits), one per batch element.
1005
+ """
1006
+ batch_size = x_start.shape[0]
1007
+ t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
1008
+ qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
1009
+ kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
1010
+ return mean_flat(kl_prior) / np.log(2.0)
1011
+
1012
+ def p_losses(self, x_start, cond, t, noise=None):
1013
+ noise = default(noise, lambda: torch.randn_like(x_start))
1014
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
1015
+ model_output = self.apply_model(x_noisy, t, cond)
1016
+
1017
+ loss_dict = {}
1018
+ prefix = 'train' if self.training else 'val'
1019
+
1020
+ if self.parameterization == "x0":
1021
+ target = x_start
1022
+ elif self.parameterization == "eps":
1023
+ target = noise
1024
+ else:
1025
+ raise NotImplementedError()
1026
+
1027
+ loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
1028
+ loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
1029
+
1030
+ logvar_t = self.logvar[t].to(self.device)
1031
+ loss = loss_simple / torch.exp(logvar_t) + logvar_t
1032
+ # loss = loss_simple / torch.exp(self.logvar) + self.logvar
1033
+ if self.learn_logvar:
1034
+ loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
1035
+ loss_dict.update({'logvar': self.logvar.data.mean()})
1036
+
1037
+ loss = self.l_simple_weight * loss.mean()
1038
+
1039
+ loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
1040
+ loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
1041
+ loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
1042
+ loss += (self.original_elbo_weight * loss_vlb)
1043
+ loss_dict.update({f'{prefix}/loss': loss})
1044
+
1045
+ return loss, loss_dict
1046
+
1047
+ def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
1048
+ return_x0=False, score_corrector=None, corrector_kwargs=None):
1049
+ t_in = t
1050
+ model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
1051
+
1052
+ if score_corrector is not None:
1053
+ assert self.parameterization == "eps"
1054
+ model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
1055
+
1056
+ if return_codebook_ids:
1057
+ model_out, logits = model_out
1058
+
1059
+ if self.parameterization == "eps":
1060
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
1061
+ elif self.parameterization == "x0":
1062
+ x_recon = model_out
1063
+ else:
1064
+ raise NotImplementedError()
1065
+
1066
+ if clip_denoised:
1067
+ x_recon.clamp_(-1., 1.)
1068
+ if quantize_denoised:
1069
+ x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
1070
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
1071
+ if return_codebook_ids:
1072
+ return model_mean, posterior_variance, posterior_log_variance, logits
1073
+ elif return_x0:
1074
+ return model_mean, posterior_variance, posterior_log_variance, x_recon
1075
+ else:
1076
+ return model_mean, posterior_variance, posterior_log_variance
1077
+
1078
+ @torch.no_grad()
1079
+ def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
1080
+ return_codebook_ids=False, quantize_denoised=False, return_x0=False,
1081
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
1082
+ b, *_, device = *x.shape, x.device
1083
+ outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
1084
+ return_codebook_ids=return_codebook_ids,
1085
+ quantize_denoised=quantize_denoised,
1086
+ return_x0=return_x0,
1087
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1088
+ if return_codebook_ids:
1089
+ raise DeprecationWarning("Support dropped.")
1090
+ model_mean, _, model_log_variance, logits = outputs
1091
+ elif return_x0:
1092
+ model_mean, _, model_log_variance, x0 = outputs
1093
+ else:
1094
+ model_mean, _, model_log_variance = outputs
1095
+
1096
+ noise = noise_like(x.shape, device, repeat_noise) * temperature
1097
+ if noise_dropout > 0.:
1098
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
1099
+ # no noise when t == 0
1100
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
1101
+
1102
+ if return_codebook_ids:
1103
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
1104
+ if return_x0:
1105
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
1106
+ else:
1107
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
1108
+
1109
+ @torch.no_grad()
1110
+ def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
1111
+ img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
1112
+ score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
1113
+ log_every_t=None):
1114
+ if not log_every_t:
1115
+ log_every_t = self.log_every_t
1116
+ timesteps = self.num_timesteps
1117
+ if batch_size is not None:
1118
+ b = batch_size if batch_size is not None else shape[0]
1119
+ shape = [batch_size] + list(shape)
1120
+ else:
1121
+ b = batch_size = shape[0]
1122
+ if x_T is None:
1123
+ img = torch.randn(shape, device=self.device)
1124
+ else:
1125
+ img = x_T
1126
+ intermediates = []
1127
+ if cond is not None:
1128
+ if isinstance(cond, dict):
1129
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1130
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1131
+ else:
1132
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1133
+
1134
+ if start_T is not None:
1135
+ timesteps = min(timesteps, start_T)
1136
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
1137
+ total=timesteps) if verbose else reversed(
1138
+ range(0, timesteps))
1139
+ if type(temperature) == float:
1140
+ temperature = [temperature] * timesteps
1141
+
1142
+ for i in iterator:
1143
+ ts = torch.full((b,), i, device=self.device, dtype=torch.long)
1144
+ if self.shorten_cond_schedule:
1145
+ assert self.model.conditioning_key != 'hybrid'
1146
+ tc = self.cond_ids[ts].to(cond.device)
1147
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1148
+
1149
+ img, x0_partial = self.p_sample(img, cond, ts,
1150
+ clip_denoised=self.clip_denoised,
1151
+ quantize_denoised=quantize_denoised, return_x0=True,
1152
+ temperature=temperature[i], noise_dropout=noise_dropout,
1153
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1154
+ if mask is not None:
1155
+ assert x0 is not None
1156
+ img_orig = self.q_sample(x0, ts)
1157
+ img = img_orig * mask + (1. - mask) * img
1158
+
1159
+ if i % log_every_t == 0 or i == timesteps - 1:
1160
+ intermediates.append(x0_partial)
1161
+ if callback: callback(i)
1162
+ if img_callback: img_callback(img, i)
1163
+ return img, intermediates
1164
+
1165
+ @torch.no_grad()
1166
+ def p_sample_loop(self, cond, shape, return_intermediates=False,
1167
+ x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
1168
+ mask=None, x0=None, img_callback=None, start_T=None,
1169
+ log_every_t=None):
1170
+
1171
+ if not log_every_t:
1172
+ log_every_t = self.log_every_t
1173
+ device = self.betas.device
1174
+ b = shape[0]
1175
+ if x_T is None:
1176
+ img = torch.randn(shape, device=device)
1177
+ else:
1178
+ img = x_T
1179
+
1180
+ intermediates = [img]
1181
+ if timesteps is None:
1182
+ timesteps = self.num_timesteps
1183
+
1184
+ if start_T is not None:
1185
+ timesteps = min(timesteps, start_T)
1186
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
1187
+ range(0, timesteps))
1188
+
1189
+ if mask is not None:
1190
+ assert x0 is not None
1191
+ assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
1192
+
1193
+ for i in iterator:
1194
+ ts = torch.full((b,), i, device=device, dtype=torch.long)
1195
+ if self.shorten_cond_schedule:
1196
+ assert self.model.conditioning_key != 'hybrid'
1197
+ tc = self.cond_ids[ts].to(cond.device)
1198
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1199
+
1200
+ img = self.p_sample(img, cond, ts,
1201
+ clip_denoised=self.clip_denoised,
1202
+ quantize_denoised=quantize_denoised)
1203
+ if mask is not None:
1204
+ img_orig = self.q_sample(x0, ts)
1205
+ img = img_orig * mask + (1. - mask) * img
1206
+
1207
+ if i % log_every_t == 0 or i == timesteps - 1:
1208
+ intermediates.append(img)
1209
+ if callback: callback(i)
1210
+ if img_callback: img_callback(img, i)
1211
+
1212
+ if return_intermediates:
1213
+ return img, intermediates
1214
+ return img
1215
+
1216
+ @torch.no_grad()
1217
+ def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
1218
+ verbose=True, timesteps=None, quantize_denoised=False,
1219
+ mask=None, x0=None, shape=None,**kwargs):
1220
+ if shape is None:
1221
+ shape = (batch_size, self.channels, self.image_size, self.image_size)
1222
+ if cond is not None:
1223
+ if isinstance(cond, dict):
1224
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1225
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1226
+ else:
1227
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1228
+ return self.p_sample_loop(cond,
1229
+ shape,
1230
+ return_intermediates=return_intermediates, x_T=x_T,
1231
+ verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
1232
+ mask=mask, x0=x0)
1233
+
1234
+ @torch.no_grad()
1235
+ def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs):
1236
+
1237
+ if ddim:
1238
+ ddim_sampler = DDIMSampler(self)
1239
+ shape = (self.channels, self.image_size, self.image_size)
1240
+ samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size,
1241
+ shape,cond,verbose=False,**kwargs)
1242
+
1243
+ else:
1244
+ samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
1245
+ return_intermediates=True,**kwargs)
1246
+
1247
+ return samples, intermediates
1248
+
1249
+
1250
+ @torch.no_grad()
1251
+ def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
1252
+ quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
1253
+ plot_diffusion_rows=True, **kwargs):
1254
+
1255
+ use_ddim = ddim_steps is not None
1256
+
1257
+ log = dict()
1258
+ z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
1259
+ return_first_stage_outputs=True,
1260
+ force_c_encode=True,
1261
+ return_original_cond=True,
1262
+ bs=N)
1263
+ N = min(x.shape[0], N)
1264
+ n_row = min(x.shape[0], n_row)
1265
+ log["inputs"] = x
1266
+ log["reconstruction"] = xrec
1267
+ if self.model.conditioning_key is not None:
1268
+ if hasattr(self.cond_stage_model, "decode"):
1269
+ xc = self.cond_stage_model.decode(c)
1270
+ log["conditioning"] = xc
1271
+ elif self.cond_stage_key in ["caption"]:
1272
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"])
1273
+ log["conditioning"] = xc
1274
+ elif self.cond_stage_key in ["class_to_node"]:
1275
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["class_to_node"])
1276
+ log["conditioning"] = xc
1277
+ elif self.cond_stage_key in ["class_name"]:
1278
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["class_name"])
1279
+ log["conditioning"] = xc
1280
+ elif self.cond_stage_key == 'class_label':
1281
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
1282
+ log['conditioning'] = xc
1283
+ elif isimage(xc):
1284
+ log["conditioning"] = xc
1285
+ if ismap(xc):
1286
+ log["original_conditioning"] = self.to_rgb(xc)
1287
+
1288
+ if plot_diffusion_rows:
1289
+ # get diffusion row
1290
+ diffusion_row = list()
1291
+ z_start = z[:n_row]
1292
+ for t in range(self.num_timesteps):
1293
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1294
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1295
+ t = t.to(self.device).long()
1296
+ noise = torch.randn_like(z_start)
1297
+ z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1298
+ diffusion_row.append(self.decode_first_stage(z_noisy))
1299
+
1300
+ diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1301
+ diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1302
+ diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1303
+ diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1304
+ log["diffusion_row"] = diffusion_grid
1305
+
1306
+ if sample:
1307
+ # get denoise row
1308
+ with self.ema_scope("Plotting"):
1309
+ samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
1310
+ ddim_steps=ddim_steps,eta=ddim_eta)
1311
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1312
+ x_samples = self.decode_first_stage(samples)
1313
+ log["samples"] = x_samples
1314
+ if plot_denoise_rows:
1315
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1316
+ log["denoise_row"] = denoise_grid
1317
+
1318
+ if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
1319
+ self.first_stage_model, IdentityFirstStage):
1320
+ # also display when quantizing x0 while sampling
1321
+ with self.ema_scope("Plotting Quantized Denoised"):
1322
+ samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
1323
+ ddim_steps=ddim_steps,eta=ddim_eta,
1324
+ quantize_denoised=True)
1325
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
1326
+ # quantize_denoised=True)
1327
+ x_samples = self.decode_first_stage(samples.to(self.device))
1328
+ log["samples_x0_quantized"] = x_samples
1329
+
1330
+ if inpaint:
1331
+ # make a simple center square
1332
+ b, h, w = z.shape[0], z.shape[2], z.shape[3]
1333
+ mask = torch.ones(N, h, w).to(self.device)
1334
+ # zeros will be filled in
1335
+ mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
1336
+ mask = mask[:, None, ...]
1337
+ with self.ema_scope("Plotting Inpaint"):
1338
+
1339
+ samples, _ = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, eta=ddim_eta,
1340
+ ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1341
+ x_samples = self.decode_first_stage(samples.to(self.device))
1342
+ log["samples_inpainting"] = x_samples
1343
+ log["mask"] = mask
1344
+
1345
+ # outpaint
1346
+ with self.ema_scope("Plotting Outpaint"):
1347
+ samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,eta=ddim_eta,
1348
+ ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1349
+ x_samples = self.decode_first_stage(samples.to(self.device))
1350
+ log["samples_outpainting"] = x_samples
1351
+
1352
+ if plot_progressive_rows:
1353
+ with self.ema_scope("Plotting Progressives"):
1354
+ img, progressives = self.progressive_denoising(c,
1355
+ shape=(self.channels, self.image_size, self.image_size),
1356
+ batch_size=N)
1357
+ prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
1358
+ log["progressive_row"] = prog_row
1359
+
1360
+ if return_keys:
1361
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
1362
+ return log
1363
+ else:
1364
+ return {key: log[key] for key in return_keys}
1365
+ return log
1366
+
1367
+ def configure_optimizers(self):
1368
+ lr = self.learning_rate
1369
+ params = list(self.model.parameters())
1370
+ if self.cond_stage_trainable:
1371
+ print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
1372
+ params = params + list(self.cond_stage_model.parameters())
1373
+ if self.learn_logvar:
1374
+ print('Diffusion model optimizing logvar')
1375
+ params.append(self.logvar)
1376
+ opt = torch.optim.AdamW(params, lr=lr)
1377
+ if self.use_scheduler:
1378
+ assert 'target' in self.scheduler_config
1379
+ scheduler = instantiate_from_config(self.scheduler_config)
1380
+
1381
+ print("Setting up LambdaLR scheduler...")
1382
+ scheduler = [
1383
+ {
1384
+ 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
1385
+ 'interval': 'step',
1386
+ 'frequency': 1
1387
+ }]
1388
+ return [opt], scheduler
1389
+ return opt
1390
+
1391
+ @torch.no_grad()
1392
+ def to_rgb(self, x):
1393
+ x = x.float()
1394
+ if not hasattr(self, "colorize"):
1395
+ self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
1396
+ x = nn.functional.conv2d(x, weight=self.colorize)
1397
+ x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
1398
+ return x
1399
+
1400
+
1401
+ class DiffusionWrapper(pl.LightningModule):
1402
+ def __init__(self, diff_model_config, conditioning_key):
1403
+ super().__init__()
1404
+ self.diffusion_model = instantiate_from_config(diff_model_config)
1405
+ self.conditioning_key = conditioning_key
1406
+ assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm']
1407
+
1408
+ def forward(self, x, t, c_concat: list = None, c_crossattn: list = None):
1409
+ if self.conditioning_key is None:
1410
+ out = self.diffusion_model(x, t)
1411
+ elif self.conditioning_key == 'concat':
1412
+ xc = torch.cat([x] + c_concat, dim=1)
1413
+ out = self.diffusion_model(xc, t)
1414
+ elif self.conditioning_key == 'crossattn':
1415
+ cc = torch.cat(c_crossattn, 1)
1416
+ out = self.diffusion_model(x, t, context=cc)
1417
+ elif self.conditioning_key == 'hybrid':
1418
+ xc = torch.cat([x] + c_concat, dim=1)
1419
+ cc = torch.cat(c_crossattn, 1)
1420
+ out = self.diffusion_model(xc, t, context=cc)
1421
+ elif self.conditioning_key == 'adm':
1422
+ cc = c_crossattn[0]
1423
+ out = self.diffusion_model(x, t, y=cc)
1424
+ else:
1425
+ raise NotImplementedError()
1426
+
1427
+ return out
1428
+
1429
+
1430
+ class Layout2ImgDiffusion(LatentDiffusion):
1431
+ # TODO: move all layout-specific hacks to this class
1432
+ def __init__(self, cond_stage_key, *args, **kwargs):
1433
+ assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
1434
+ super().__init__(cond_stage_key=cond_stage_key, *args, **kwargs)
1435
+
1436
+ def log_images(self, batch, N=8, *args, **kwargs):
1437
+ logs = super().log_images(batch=batch, N=N, *args, **kwargs)
1438
+
1439
+ key = 'train' if self.training else 'validation'
1440
+ dset = self.trainer.datamodule.datasets[key]
1441
+ mapper = dset.conditional_builders[self.cond_stage_key]
1442
+
1443
+ bbox_imgs = []
1444
+ map_fn = lambda catno: dset.get_textual_label(dset.get_category_id(catno))
1445
+ for tknzd_bbox in batch[self.cond_stage_key][:N]:
1446
+ bboximg = mapper.plot(tknzd_bbox.detach().cpu(), map_fn, (256, 256))
1447
+ bbox_imgs.append(bboximg)
1448
+
1449
+ cond_img = torch.stack(bbox_imgs, dim=0)
1450
+ logs['bbox_image'] = cond_img
1451
+ return logs
ldm/models/diffusion/plms.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+
11
+ class PLMSSampler(object):
12
+ def __init__(self, model, schedule="linear", **kwargs):
13
+ super().__init__()
14
+ self.model = model
15
+ self.ddpm_num_timesteps = model.num_timesteps
16
+ self.schedule = schedule
17
+
18
+ def register_buffer(self, name, attr):
19
+ if type(attr) == torch.Tensor:
20
+ if attr.device != torch.device("cuda"):
21
+ attr = attr.to(torch.device("cuda"))
22
+ setattr(self, name, attr)
23
+
24
+ def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
25
+ if ddim_eta != 0:
26
+ raise ValueError('ddim_eta must be 0 for PLMS')
27
+ self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
28
+ num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
29
+ alphas_cumprod = self.model.alphas_cumprod
30
+ assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
31
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
32
+
33
+ self.register_buffer('betas', to_torch(self.model.betas))
34
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
35
+ self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
36
+
37
+ # calculations for diffusion q(x_t | x_{t-1}) and others
38
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
39
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
40
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
41
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
42
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
43
+
44
+ # ddim sampling parameters
45
+ ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
46
+ ddim_timesteps=self.ddim_timesteps,
47
+ eta=ddim_eta,verbose=verbose)
48
+ self.register_buffer('ddim_sigmas', ddim_sigmas)
49
+ self.register_buffer('ddim_alphas', ddim_alphas)
50
+ self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
51
+ self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
52
+ sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
53
+ (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
54
+ 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
55
+ self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
56
+
57
+ @torch.no_grad()
58
+ def sample(self,
59
+ S,
60
+ batch_size,
61
+ shape,
62
+ conditioning=None,
63
+ callback=None,
64
+ normals_sequence=None,
65
+ img_callback=None,
66
+ quantize_x0=False,
67
+ eta=0.,
68
+ mask=None,
69
+ x0=None,
70
+ temperature=1.,
71
+ noise_dropout=0.,
72
+ score_corrector=None,
73
+ corrector_kwargs=None,
74
+ verbose=True,
75
+ x_T=None,
76
+ log_every_t=100,
77
+ unconditional_guidance_scale=1.,
78
+ unconditional_conditioning=None,
79
+ # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
80
+ **kwargs
81
+ ):
82
+ if conditioning is not None:
83
+ if isinstance(conditioning, dict):
84
+ cbs = conditioning[list(conditioning.keys())[0]].shape[0]
85
+ if cbs != batch_size:
86
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
87
+ else:
88
+ if conditioning.shape[0] != batch_size:
89
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
90
+
91
+ self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
92
+ # sampling
93
+ C, H, W = shape
94
+ size = (batch_size, C, H, W)
95
+ print(f'Data shape for PLMS sampling is {size}')
96
+
97
+ samples, intermediates = self.plms_sampling(conditioning, size,
98
+ callback=callback,
99
+ img_callback=img_callback,
100
+ quantize_denoised=quantize_x0,
101
+ mask=mask, x0=x0,
102
+ ddim_use_original_steps=False,
103
+ noise_dropout=noise_dropout,
104
+ temperature=temperature,
105
+ score_corrector=score_corrector,
106
+ corrector_kwargs=corrector_kwargs,
107
+ x_T=x_T,
108
+ log_every_t=log_every_t,
109
+ unconditional_guidance_scale=unconditional_guidance_scale,
110
+ unconditional_conditioning=unconditional_conditioning,
111
+ )
112
+ return samples, intermediates
113
+
114
+ @torch.no_grad()
115
+ def plms_sampling(self, cond, shape,
116
+ x_T=None, ddim_use_original_steps=False,
117
+ callback=None, timesteps=None, quantize_denoised=False,
118
+ mask=None, x0=None, img_callback=None, log_every_t=100,
119
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
120
+ unconditional_guidance_scale=1., unconditional_conditioning=None,):
121
+ device = self.model.betas.device
122
+ b = shape[0]
123
+ if x_T is None:
124
+ img = torch.randn(shape, device=device)
125
+ else:
126
+ img = x_T
127
+
128
+ if timesteps is None:
129
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
130
+ elif timesteps is not None and not ddim_use_original_steps:
131
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
132
+ timesteps = self.ddim_timesteps[:subset_end]
133
+
134
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
135
+ time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps)
136
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
137
+ print(f"Running PLMS Sampling with {total_steps} timesteps")
138
+
139
+ iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps)
140
+ old_eps = []
141
+
142
+ for i, step in enumerate(iterator):
143
+ index = total_steps - i - 1
144
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
145
+ ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long)
146
+
147
+ if mask is not None:
148
+ assert x0 is not None
149
+ img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
150
+ img = img_orig * mask + (1. - mask) * img
151
+
152
+ outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
153
+ quantize_denoised=quantize_denoised, temperature=temperature,
154
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
155
+ corrector_kwargs=corrector_kwargs,
156
+ unconditional_guidance_scale=unconditional_guidance_scale,
157
+ unconditional_conditioning=unconditional_conditioning,
158
+ old_eps=old_eps, t_next=ts_next)
159
+ img, pred_x0, e_t = outs
160
+ old_eps.append(e_t)
161
+ if len(old_eps) >= 4:
162
+ old_eps.pop(0)
163
+ if callback: callback(i)
164
+ if img_callback: img_callback(pred_x0, i)
165
+
166
+ if index % log_every_t == 0 or index == total_steps - 1:
167
+ intermediates['x_inter'].append(img)
168
+ intermediates['pred_x0'].append(pred_x0)
169
+
170
+ return img, intermediates
171
+
172
+ @torch.no_grad()
173
+ def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
174
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
175
+ unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None):
176
+ b, *_, device = *x.shape, x.device
177
+
178
+ def get_model_output(x, t):
179
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
180
+ e_t = self.model.apply_model(x, t, c)
181
+ else:
182
+ x_in = torch.cat([x] * 2)
183
+ t_in = torch.cat([t] * 2)
184
+ c_in = torch.cat([unconditional_conditioning, c])
185
+ e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
186
+ e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
187
+
188
+ if score_corrector is not None:
189
+ assert self.model.parameterization == "eps"
190
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
191
+
192
+ return e_t
193
+
194
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
195
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
196
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
197
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
198
+
199
+ def get_x_prev_and_pred_x0(e_t, index):
200
+ # select parameters corresponding to the currently considered timestep
201
+ a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
202
+ a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
203
+ sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
204
+ sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
205
+
206
+ # current prediction for x_0
207
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
208
+ if quantize_denoised:
209
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
210
+ # direction pointing to x_t
211
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
212
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
213
+ if noise_dropout > 0.:
214
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
215
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
216
+ return x_prev, pred_x0
217
+
218
+ e_t = get_model_output(x, t)
219
+ if len(old_eps) == 0:
220
+ # Pseudo Improved Euler (2nd order)
221
+ x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index)
222
+ e_t_next = get_model_output(x_prev, t_next)
223
+ e_t_prime = (e_t + e_t_next) / 2
224
+ elif len(old_eps) == 1:
225
+ # 2nd order Pseudo Linear Multistep (Adams-Bashforth)
226
+ e_t_prime = (3 * e_t - old_eps[-1]) / 2
227
+ elif len(old_eps) == 2:
228
+ # 3nd order Pseudo Linear Multistep (Adams-Bashforth)
229
+ e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12
230
+ elif len(old_eps) >= 3:
231
+ # 4nd order Pseudo Linear Multistep (Adams-Bashforth)
232
+ e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24
233
+
234
+ x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index)
235
+
236
+ return x_prev, pred_x0, e_t
ldm/models/disentanglement/__pycache__/iterative_normalization.cpython-38.pyc ADDED
Binary file (10.2 kB). View file
 
ldm/models/disentanglement/iterative_normalization.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reference: Concept Whitening for Interpretable Image Recognition
3
+ - Paper: https://arxiv.org/pdf/2002.01650.pdf
4
+ - Code: https://github.com/zhiCHEN96/ConceptWhitening
5
+ """
6
+ import torch.nn
7
+ import torch.nn.functional as F
8
+ from torch.nn import Parameter
9
+
10
+ # import extension._bcnn as bcnn
11
+
12
+ __all__ = ['iterative_normalization', 'IterNorm']
13
+
14
+ class iterative_normalization_py(torch.autograd.Function):
15
+ @staticmethod
16
+ def forward(ctx, *args, **kwargs):
17
+ X, running_mean, running_wmat, nc, ctx.T, eps, momentum, training = args
18
+ # change NxCxHxW to (G x D) x(NxHxW), i.e., g*d*m
19
+ ctx.g = X.size(1) // nc
20
+ x = X.transpose(0, 1).contiguous().view(ctx.g, nc, -1)
21
+ _, d, m = x.size()
22
+ saved = []
23
+ if training:
24
+ # calculate centered activation by subtracted mini-batch mean
25
+ mean = x.mean(-1, keepdim=True)
26
+ xc = x - mean
27
+ saved.append(xc)
28
+ # calculate covariance matrix
29
+ P = [None] * (ctx.T + 1)
30
+ P[0] = torch.eye(d).to(X).expand(ctx.g, d, d)
31
+ Sigma = torch.baddbmm(eps, P[0], 1. / m, xc, xc.transpose(1, 2))
32
+ # reciprocal of trace of Sigma: shape [g, 1, 1]
33
+ rTr = (Sigma * P[0]).sum((1, 2), keepdim=True).reciprocal_()
34
+ saved.append(rTr)
35
+ Sigma_N = Sigma * rTr
36
+ saved.append(Sigma_N)
37
+ for k in range(ctx.T):
38
+ P[k + 1] = torch.baddbmm(1.5, P[k], -0.5, torch.matrix_power(P[k], 3), Sigma_N)
39
+ saved.extend(P)
40
+ wm = P[ctx.T].mul_(rTr.sqrt()) # whiten matrix: the matrix inverse of Sigma, i.e., Sigma^{-1/2}
41
+ running_mean.copy_(momentum * mean + (1. - momentum) * running_mean)
42
+ running_wmat.copy_(momentum * wm + (1. - momentum) * running_wmat)
43
+ else:
44
+ xc = x - running_mean
45
+ wm = running_wmat
46
+ xn = wm.matmul(xc)
47
+ Xn = xn.view(X.size(1), X.size(0), *X.size()[2:]).transpose(0, 1).contiguous()
48
+ ctx.save_for_backward(*saved)
49
+ return Xn
50
+
51
+ @staticmethod
52
+ def backward(ctx, *grad_outputs):
53
+ grad, = grad_outputs
54
+ saved = ctx.saved_variables
55
+ xc = saved[0] # centered input
56
+ rTr = saved[1] # trace of Sigma
57
+ sn = saved[2].transpose(-2, -1) # normalized Sigma
58
+ P = saved[3:] # middle result matrix,
59
+ g, d, m = xc.size()
60
+
61
+ g_ = grad.transpose(0, 1).contiguous().view_as(xc)
62
+ g_wm = g_.matmul(xc.transpose(-2, -1))
63
+ g_P = g_wm * rTr.sqrt()
64
+ wm = P[ctx.T]
65
+ g_sn = 0
66
+ for k in range(ctx.T, 1, -1):
67
+ P[k - 1].transpose_(-2, -1)
68
+ P2 = P[k - 1].matmul(P[k - 1])
69
+ g_sn += P2.matmul(P[k - 1]).matmul(g_P)
70
+ g_tmp = g_P.matmul(sn)
71
+ g_P.baddbmm_(1.5, -0.5, g_tmp, P2)
72
+ g_P.baddbmm_(1, -0.5, P2, g_tmp)
73
+ g_P.baddbmm_(1, -0.5, P[k - 1].matmul(g_tmp), P[k - 1])
74
+ g_sn += g_P
75
+ # g_sn = g_sn * rTr.sqrt()
76
+ g_tr = ((-sn.matmul(g_sn) + g_wm.transpose(-2, -1).matmul(wm)) * P[0]).sum((1, 2), keepdim=True) * P[0]
77
+ g_sigma = (g_sn + g_sn.transpose(-2, -1) + 2. * g_tr) * (-0.5 / m * rTr)
78
+ # g_sigma = g_sigma + g_sigma.transpose(-2, -1)
79
+ g_x = torch.baddbmm(wm.matmul(g_ - g_.mean(-1, keepdim=True)), g_sigma, xc)
80
+ grad_input = g_x.view(grad.size(1), grad.size(0), *grad.size()[2:]).transpose(0, 1).contiguous()
81
+ return grad_input, None, None, None, None, None, None, None
82
+
83
+
84
+ class IterNorm(torch.nn.Module):
85
+ def __init__(self, num_features, num_groups=1, num_channels=None, T=5, dim=4, eps=1e-5, momentum=0.1, affine=True,
86
+ *args, **kwargs):
87
+ super(IterNorm, self).__init__()
88
+ # assert dim == 4, 'IterNorm is not support 2D'
89
+ self.T = T
90
+ self.eps = eps
91
+ self.momentum = momentum
92
+ self.num_features = num_features
93
+ self.affine = affine
94
+ self.dim = dim
95
+ if num_channels is None:
96
+ num_channels = (num_features - 1) // num_groups + 1
97
+ num_groups = num_features // num_channels
98
+ while num_features % num_channels != 0:
99
+ num_channels //= 2
100
+ num_groups = num_features // num_channels
101
+ assert num_groups > 0 and num_features % num_groups == 0, "num features={}, num groups={}".format(num_features,
102
+ num_groups)
103
+ self.num_groups = num_groups
104
+ self.num_channels = num_channels
105
+ shape = [1] * dim
106
+ shape[1] = self.num_features
107
+ if self.affine:
108
+ self.weight = Parameter(torch.Tensor(*shape))
109
+ self.bias = Parameter(torch.Tensor(*shape))
110
+ else:
111
+ self.register_parameter('weight', None)
112
+ self.register_parameter('bias', None)
113
+
114
+ self.register_buffer('running_mean', torch.zeros(num_groups, num_channels, 1))
115
+ # running whiten matrix
116
+ self.register_buffer('running_wm', torch.eye(num_channels).expand(num_groups, num_channels, num_channels))
117
+ self.reset_parameters()
118
+
119
+ def reset_parameters(self):
120
+ # self.reset_running_stats()
121
+ if self.affine:
122
+ torch.nn.init.ones_(self.weight)
123
+ torch.nn.init.zeros_(self.bias)
124
+
125
+ def forward(self, X: torch.Tensor):
126
+ X_hat = iterative_normalization_py.apply(X, self.running_mean, self.running_wm, self.num_channels, self.T,
127
+ self.eps, self.momentum, self.training)
128
+ # affine
129
+ if self.affine:
130
+ return X_hat * self.weight + self.bias
131
+ else:
132
+ return X_hat
133
+
134
+ def extra_repr(self):
135
+ return '{num_features}, num_channels={num_channels}, T={T}, eps={eps}, ' \
136
+ 'momentum={momentum}, affine={affine}'.format(**self.__dict__)
137
+
138
+
139
+ class IterNormRotation(torch.nn.Module):
140
+ """
141
+ Concept Whitening Module
142
+ The Whitening part is adapted from IterNorm. The core of CW module is learning
143
+ an extra rotation matrix R that align target concepts with the output feature
144
+ maps.
145
+
146
+ Because the concept activation is calculated based on a feature map, which
147
+ is a matrix, there are multiple ways to calculate the activation, denoted
148
+ by activation_mode.
149
+ """
150
+ def __init__(self, num_features, num_groups = 1, num_channels=None, T=10, dim=4, eps=1e-5, momentum=0.05, affine=False,
151
+ mode = -1, activation_mode='pool_max', *args, **kwargs):
152
+ super(IterNormRotation, self).__init__()
153
+ assert dim == 4, 'IterNormRotation does not support 2D'
154
+ self.T = T
155
+ self.eps = eps
156
+ self.momentum = momentum
157
+ self.num_features = num_features
158
+ self.affine = affine
159
+ self.dim = dim
160
+ self.mode = mode
161
+ self.activation_mode = activation_mode
162
+
163
+ assert num_groups == 1, 'Please keep num_groups = 1. Current version does not support group whitening.'
164
+ if num_channels is None:
165
+ num_channels = (num_features - 1) // num_groups + 1
166
+ num_groups = num_features // num_channels
167
+ while num_features % num_channels != 0:
168
+ num_channels //= 2
169
+ num_groups = num_features // num_channels
170
+ assert num_groups > 0 and num_features % num_groups == 0, "num features={}, num groups={}".format(num_features,
171
+ num_groups)
172
+
173
+ self.num_groups = num_groups
174
+ self.num_channels = num_channels
175
+ shape = [1] * dim
176
+ shape[1] = self.num_features
177
+ #if self.affine:
178
+ self.weight = Parameter(torch.Tensor(*shape))
179
+ self.bias = Parameter(torch.Tensor(*shape))
180
+ #else:
181
+ # self.register_parameter('weight', None)
182
+ # self.register_parameter('bias', None)
183
+
184
+ #pooling and unpooling used in gradient computation
185
+ self.maxpool = torch.nn.MaxPool2d(kernel_size=3, stride=3, return_indices=True)
186
+ self.maxunpool = torch.nn.MaxUnpool2d(kernel_size=3, stride=3)
187
+
188
+ # running mean
189
+ self.register_buffer('running_mean', torch.zeros(num_groups, num_channels, 1))
190
+ # running whiten matrix
191
+ self.register_buffer('running_wm', torch.eye(num_channels).expand(num_groups, num_channels, num_channels))
192
+ # running rotation matrix
193
+ self.register_buffer('running_rot', torch.eye(num_channels).expand(num_groups, num_channels, num_channels))
194
+ # sum Gradient, need to take average later
195
+ self.register_buffer('sum_G', torch.zeros(num_groups, num_channels, num_channels))
196
+ # counter, number of gradient for each concept
197
+ self.register_buffer("counter", torch.ones(num_channels)*0.001)
198
+
199
+ self.reset_parameters()
200
+
201
+ def reset_parameters(self):
202
+ if self.affine:
203
+ torch.nn.init.ones_(self.weight)
204
+ torch.nn.init.zeros_(self.bias)
205
+
206
+ def update_rotation_matrix(self):
207
+ """
208
+ Update the rotation matrix R using the accumulated gradient G.
209
+ The update uses Cayley transform to make sure R is always orthonormal.
210
+ """
211
+ size_R = self.running_rot.size()
212
+ with torch.no_grad():
213
+ G = self.sum_G/self.counter.reshape(-1,1)
214
+ R = self.running_rot.clone()
215
+ for i in range(2):
216
+ tau = 1000 # learning rate in Cayley transform
217
+ alpha = 0
218
+ beta = 100000000
219
+ c1 = 1e-4
220
+ c2 = 0.9
221
+
222
+ A = torch.einsum('gin,gjn->gij', G, R) - torch.einsum('gin,gjn->gij', R, G) # GR^T - RG^T
223
+ I = torch.eye(size_R[2]).expand(*size_R).cuda()
224
+ dF_0 = -0.5 * (A ** 2).sum()
225
+ # binary search for appropriate learning rate
226
+ cnt = 0
227
+ while True:
228
+ Q = torch.bmm((I + 0.5 * tau * A).inverse(), I - 0.5 * tau * A)
229
+ Y_tau = torch.bmm(Q, R)
230
+ F_X = (G[:,:,:] * R[:,:,:]).sum()
231
+ F_Y_tau = (G[:,:,:] * Y_tau[:,:,:]).sum()
232
+ dF_tau = -torch.bmm(torch.einsum('gni,gnj->gij', G, (I + 0.5 * tau * A).inverse()), torch.bmm(A,0.5*(R+Y_tau)))[0,:,:].trace()
233
+ if F_Y_tau > F_X + c1*tau*dF_0 + 1e-18:
234
+ beta = tau
235
+ tau = (beta+alpha)/2
236
+ elif dF_tau + 1e-18 < c2*dF_0:
237
+ alpha = tau
238
+ tau = (beta+alpha)/2
239
+ else:
240
+ break
241
+ cnt += 1
242
+ if cnt > 500:
243
+ print("--------------------update fail------------------------")
244
+ print(F_Y_tau, F_X + c1*tau*dF_0)
245
+ print(dF_tau, c2*dF_0)
246
+ print("-------------------------------------------------------")
247
+ break
248
+ print(tau, F_Y_tau)
249
+ Q = torch.bmm((I + 0.5 * tau * A).inverse(), I - 0.5 * tau * A)
250
+ R = torch.bmm(Q, R)
251
+
252
+ self.running_rot = R
253
+ self.counter = (torch.ones(size_R[-1]) * 0.001).cuda()
254
+
255
+
256
+ def forward(self, X: torch.Tensor):
257
+ X_hat = iterative_normalization_py.apply(X, self.running_mean, self.running_wm, self.num_channels, self.T,
258
+ self.eps, self.momentum, self.training)
259
+ # print(X_hat.shape, self.running_rot.shape)
260
+ # nchw
261
+ size_X = X_hat.size()
262
+ size_R = self.running_rot.size()
263
+ # ngchw
264
+ X_hat = X_hat.view(size_X[0], size_R[0], size_R[2], *size_X[2:])
265
+ # updating the gradient matrix, using the concept dataset
266
+ # the gradient is accumulated with momentum to stablize the training
267
+ with torch.no_grad():
268
+ # When 0<=mode, the jth column of gradient matrix is accumulated
269
+ if self.mode>=0:
270
+ if self.activation_mode=='mean':
271
+ self.sum_G[:,self.mode,:] = self.momentum * -X_hat.mean((0,3,4)) + (1. - self.momentum) * self.sum_G[:,self.mode,:]
272
+ self.counter[self.mode] += 1
273
+ elif self.activation_mode=='max':
274
+ X_test = torch.einsum('bgchw,gdc->bgdhw', X_hat, self.running_rot)
275
+ max_values = torch.max(torch.max(X_test, 3, keepdim=True)[0], 4, keepdim=True)[0]
276
+ max_bool = max_values==X_test
277
+ grad = -((X_hat * max_bool.to(X_hat)).sum((3,4))/max_bool.to(X_hat).sum((3,4))).mean((0,))
278
+ self.sum_G[:,self.mode,:] = self.momentum * grad + (1. - self.momentum) * self.sum_G[:,self.mode,:]
279
+ self.counter[self.mode] += 1
280
+ elif self.activation_mode=='pos_mean':
281
+ X_test = torch.einsum('bgchw,gdc->bgdhw', X_hat, self.running_rot)
282
+ pos_bool = X_test > 0
283
+ grad = -((X_hat * pos_bool.to(X_hat)).sum((3,4))/(pos_bool.to(X_hat).sum((3,4))+0.0001)).mean((0,))
284
+ self.sum_G[:,self.mode,:] = self.momentum * grad + (1. - self.momentum) * self.sum_G[:,self.mode,:]
285
+ self.counter[self.mode] += 1
286
+ elif self.activation_mode=='pool_max':
287
+ X_test = torch.einsum('bgchw,gdc->bgdhw', X_hat, self.running_rot)
288
+ X_test_nchw = X_test.view(size_X)
289
+ maxpool_value, maxpool_indices = self.maxpool(X_test_nchw)
290
+ X_test_unpool = self.maxunpool(maxpool_value, maxpool_indices, output_size = size_X).view(size_X[0], size_R[0], size_R[2], *size_X[2:])
291
+ maxpool_bool = X_test == X_test_unpool
292
+ grad = -((X_hat * maxpool_bool.to(X_hat)).sum((3,4))/(maxpool_bool.to(X_hat).sum((3,4)))).mean((0,))
293
+ self.sum_G[:,self.mode,:] = self.momentum * grad + (1. - self.momentum) * self.sum_G[:,self.mode,:]
294
+ self.counter[self.mode] += 1
295
+ # # When mode > k, this is not included in the paper
296
+ # elif self.mode>=0 and self.mode>=self.k:
297
+ # X_dot = torch.einsum('ngchw,gdc->ngdhw', X_hat, self.running_rot)
298
+ # X_dot = (X_dot == torch.max(X_dot, dim=2,keepdim=True)[0]).float().cuda()
299
+ # X_dot_unity = torch.clamp(torch.ceil(X_dot), 0.0, 1.0)
300
+ # X_G = torch.einsum('ngchw,ngdhw->gdchw', X_hat, X_dot_unity).mean((3,4))
301
+ # X_G[:,:self.k,:] = 0.0
302
+ # self.sum_G[:,:,:] += -X_G/size_X[0]
303
+ # self.counter[self.k:] += 1
304
+
305
+ # We set mode = -1 when we don't need to update G. For example, when we train for main objective
306
+ X_hat = torch.einsum('bgchw,gdc->bgdhw', X_hat, self.running_rot)
307
+ X_hat = X_hat.view(*size_X)
308
+ if self.affine:
309
+ return X_hat * self.weight + self.bias
310
+ else:
311
+ return X_hat
312
+
313
+ def extra_repr(self):
314
+ return '{num_features}, num_channels={num_channels}, T={T}, eps={eps}, ' \
315
+ 'momentum={momentum}, affine={affine}'.format(**self.__dict__)
316
+
317
+ if __name__ == '__main__':
318
+ ItN = IterNormRotation(64, num_groups=2, T=10, momentum=1, affine=False)
319
+ print(ItN)
320
+ ItN.train()
321
+ x = torch.randn(16, 64, 14, 14)
322
+ x.requires_grad_()
323
+ y = ItN(x)
324
+ z = y.transpose(0, 1).contiguous().view(x.size(1), -1)
325
+ print(z.matmul(z.t()) / z.size(1))
326
+
327
+ y.sum().backward()
328
+ print('x grad', x.grad.size())
329
+
330
+ ItN.eval()
331
+ y = ItN(x)
332
+ z = y.transpose(0, 1).contiguous().view(x.size(1), -1)
333
+ print(z.matmul(z.t()) / z.size(1))
ldm/models/phylo_include.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from scripts.import_utils import instantiate_from_config
2
+ from scripts.modules.losses.phyloloss import get_loss_name
3
+ from scripts.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
4
+ from scripts.models.vqgan import VQModel
5
+ from scripts.models.phyloautoencoder import PhyloVQVAE
6
+ from scripts.analysis_utils import Embedding_Code_converter
7
+ import scripts.constants as CONSTANTS
8
+
9
+
10
+ import torch
11
+ from torch import nn
12
+ import numpy
13
+ from torchinfo import summary
14
+ import itertools
15
+ import math
16
+
17
+ class PhyloLDM(PhyloVQVAE):
18
+ def __init__(self, **args):
19
+ print(args)
20
+
21
+ # For wandb
22
+ self.save_hyperparameters()
23
+ self.freeze()
24
+
25
+ # # self.phylo_disentangler = PhyloDisentangler(**phylo_args)
26
+ # self.phylo_disentangler = PhyloDisentanglerConv(**phylo_args)
27
+
28
+ # self.verbose = phylo_args.get('verbose', False)
29
+
ldm/models/vqgan_dual.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import pytorch_lightning as pl
4
+
5
+ from main import instantiate_from_config
6
+
7
+ from ldm.modules.diffusionmodules.model import Encoder, Decoder
8
+ from ldm.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
9
+
10
+
11
+ class VQModelDual(pl.LightningModule):
12
+ def __init__(self,
13
+ ddconfig,
14
+ lossconfig,
15
+ n_embed,
16
+ embed_dim,
17
+ ckpt_path=None,
18
+ ignore_keys=[],
19
+ image1_key="image1",
20
+ image2_key="image2",
21
+ colorize_nlabels=None,
22
+ monitor=None,
23
+ remap=None,
24
+ sane_index_shape=False, # tell vector quantizer to return indices as bhw
25
+ ):
26
+ super().__init__()
27
+ self.image1_key = image1_key
28
+ self.image2_key = image2_key
29
+
30
+ self.encoder = {}
31
+ self.decoder = {}
32
+ self.quantize = {}
33
+ self.quant_conv = {}
34
+ self.post_quant_conv = {}
35
+ self.loss = {}
36
+
37
+ for i in range(2):
38
+ self.encoder[i+1] = Encoder(**ddconfig)
39
+ self.decoder[i+1] = Decoder(**ddconfig)
40
+ self.quantize[i+1] = VectorQuantizer(n_embed, embed_dim, beta=0.25,
41
+ remap=remap, sane_index_shape=sane_index_shape)
42
+ self.quant_conv[i+1] = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
43
+ self.post_quant_conv[i+1] = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
44
+ self.loss[i+1] = instantiate_from_config(lossconfig)
45
+
46
+ if ckpt_path is not None:
47
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
48
+
49
+ if colorize_nlabels is not None:
50
+ assert type(colorize_nlabels)==int
51
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
52
+ if monitor is not None:
53
+ self.monitor = monitor
54
+
55
+ def init_from_ckpt(self, path, ignore_keys=list()):
56
+ sd = torch.load(path, map_location="cpu")["state_dict"]
57
+ keys = list(sd.keys())
58
+ for k in keys:
59
+ for ik in ignore_keys:
60
+ if k.startswith(ik):
61
+ print("Deleting key {} from state_dict.".format(k))
62
+ del sd[k]
63
+ self.load_state_dict(sd, strict=False)
64
+ print(f"Restored from {path}")
65
+
66
+ def encode(self, x, model_key):
67
+ h = self.encoder[model_key](x)
68
+ h = self.quant_conv[model_key](h)
69
+ quant, emb_loss, info = self.quantize[model_key](h)
70
+ return quant, emb_loss, info
71
+
72
+ def decode(self, quant, model_key):
73
+ quant = self.post_quant_conv[model_key](quant)
74
+ dec = self.decoder[model_key](quant)
75
+ return dec
76
+
77
+ def decode_code(self, code_b, model_key):
78
+ quant_b = self.quantize[model_key].embed_code(code_b)
79
+ dec = self.decode(quant_b,model_key)
80
+ return dec
81
+
82
+ def forward(self, input, model_key):
83
+ quant, diff, _ = self.encode(input, model_key)
84
+ dec = self.decode(quant, model_key)
85
+ return dec, diff
86
+
87
+ def get_input(self, batch, k):
88
+ x = batch[k]
89
+ if len(x.shape) == 3:
90
+ x = x[..., None]
91
+ x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format)
92
+ return x.float()
93
+
94
+ def training_step(self, batch, batch_idx, optimizer_idx):
95
+ breakpoint()
96
+ x1 = self.get_input(batch, self.image_key1)
97
+ x2 = self.get_input(batch, self.image_key2)
98
+ xrec1, qloss1 = self.forward(x1, model_key=1)
99
+ xrec2, qloss2 = self.forward(x2, model_key=2)
100
+
101
+
102
+ if optimizer_idx == 0:
103
+ # autoencoder 1
104
+ aeloss1, log_dict_ae1 = self.loss[1](qloss1, x1, xrec1, optimizer_idx, self.global_step,
105
+ last_layer=self.get_last_layer(), split="train")
106
+
107
+ self.log("train/aeloss1", aeloss1, prog_bar=True, logger=True, on_step=True, on_epoch=True)
108
+ self.log_dict(log_dict_ae1, prog_bar=False, logger=True, on_step=True, on_epoch=True)
109
+
110
+ # autoencoder 2
111
+ aeloss2, log_dict_ae2 = self.loss[2](qloss2, x2, xrec2, optimizer_idx, self.global_step,
112
+ last_layer=self.get_last_layer(), split="train")
113
+
114
+ self.log("train/aeloss2", aeloss2, prog_bar=True, logger=True, on_step=True, on_epoch=True)
115
+ self.log_dict(log_dict_ae2, prog_bar=False, logger=True, on_step=True, on_epoch=True)
116
+
117
+ return aeloss1 + aeloss2
118
+
119
+ if optimizer_idx == 1:
120
+ # discriminator 1
121
+ discloss1, log_dict_disc1 = self.loss[1](qloss1, x1, xrec1, optimizer_idx, self.global_step,
122
+ last_layer=self.get_last_layer(), split="train")
123
+ self.log("train/discloss1", discloss1, prog_bar=True, logger=True, on_step=True, on_epoch=True)
124
+ self.log_dict(log_dict_disc1, prog_bar=False, logger=True, on_step=True, on_epoch=True)
125
+
126
+ # discriminator 2
127
+ discloss2, log_dict_disc2 = self.loss[2](qloss2, x2, xrec2, optimizer_idx, self.global_step,
128
+ last_layer=self.get_last_layer(), split="train")
129
+ self.log("train/discloss", discloss2, prog_bar=True, logger=True, on_step=True, on_epoch=True)
130
+ self.log_dict(log_dict_disc2, prog_bar=False, logger=True, on_step=True, on_epoch=True)
131
+
132
+ return discloss1 + discloss2
133
+
134
+ def validation_step(self, batch, batch_idx):
135
+ breakpoint()
136
+
137
+ x1 = self.get_input(batch, self.image_key1)
138
+ x2 = self.get_input(batch, self.image_key2)
139
+ xrec1, qloss1 = self.forward(x1, model_key=1)
140
+ xrec2, qloss2 = self.forward(x2, model_key=2)
141
+
142
+
143
+ aeloss1, log_dict_ae1 = self.loss[1](qloss1, x1, xrec1, 0, self.global_step,
144
+ last_layer=self.get_last_layer(model_key=1), split="val")
145
+ aeloss2, log_dict_ae2 = self.loss[2](qloss2, x2, xrec2, 0, self.global_step,
146
+ last_layer=self.get_last_layer(model_key=2), split="val")
147
+
148
+ discloss1, log_dict_disc1 = self.loss[1](qloss1, x1, xrec1, 1, self.global_step,
149
+ last_layer=self.get_last_layer(model_key=1), split="val")
150
+ discloss2, log_dict_disc2 = self.loss[2](qloss2, x2, xrec2, 1, self.global_step,
151
+ last_layer=self.get_last_layer(model_key=2), split="val")
152
+
153
+ rec_loss1 = log_dict_ae1["val/rec_loss"]
154
+ rec_loss2 = log_dict_ae2["val/rec_loss"]
155
+ self.log("val/rec_loss1", rec_loss1,
156
+ prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
157
+ self.log("val/rec_loss2", rec_loss2,
158
+ prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
159
+ self.log("val/aeloss1", aeloss1,
160
+ prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
161
+ self.log("val/aeloss2", aeloss2,
162
+ prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
163
+ self.log_dict(log_dict_ae1)
164
+ self.log_dict(log_dict_disc1)
165
+ self.log_dict(log_dict_ae2)
166
+ self.log_dict(log_dict_disc2)
167
+ return self.log_dict
168
+
169
+ def configure_optimizers(self):
170
+ lr = self.learning_rate
171
+ opt_ae = torch.optim.Adam(list(self.encoder[1].parameters())+
172
+ list(self.decoder[1].parameters())+
173
+ list(self.quantize[1].parameters())+
174
+ list(self.quant_conv[1].parameters())+
175
+ list(self.post_quant_conv[1].parameters())+
176
+ list(self.encoder[2].parameters())+
177
+ list(self.decoder[2].parameters())+
178
+ list(self.quantize[2].parameters())+
179
+ list(self.quant_conv[2].parameters())+
180
+ list(self.post_quant_conv[2].parameters()),
181
+ lr=lr, betas=(0.5, 0.9))
182
+ opt_disc = torch.optim.Adam(list(self.loss[1].discriminator.parameters())+
183
+ list(self.loss[2].discriminator.parameters()),
184
+ lr=lr, betas=(0.5, 0.9))
185
+ return [opt_ae, opt_disc], []
186
+
187
+ def get_last_layer(self, model_key):
188
+ return self.decoder[model_key].conv_out.weight
189
+
190
+ def log_images(self, batch, **kwargs):
191
+ log = dict()
192
+
193
+ ## log 1
194
+ x = self.get_input(batch, self.image_key1)
195
+ x = x.to(self.device)
196
+ xrec, _ = self(x)
197
+ if x.shape[1] > 3:
198
+ # colorize with random projection
199
+ assert xrec.shape[1] > 3
200
+ x = self.to_rgb(x)
201
+ xrec = self.to_rgb(xrec)
202
+ log["inputs1"] = x
203
+ log["reconstructions1"] = xrec
204
+
205
+
206
+ ## log 2
207
+ x = self.get_input(batch, self.image_key2)
208
+ x = x.to(self.device)
209
+ xrec, _ = self(x)
210
+ if x.shape[1] > 3:
211
+ # colorize with random projection
212
+ assert xrec.shape[1] > 3
213
+ x = self.to_rgb(x)
214
+ xrec = self.to_rgb(xrec)
215
+ log["inputs2"] = x
216
+ log["reconstructions2"] = xrec
217
+ return log
218
+
219
+ def to_rgb(self, x):
220
+ assert self.image_key == "segmentation"
221
+ if not hasattr(self, "colorize"):
222
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
223
+ x = F.conv2d(x, weight=self.colorize)
224
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
225
+ return x
ldm/models/vqgan_dual_non_dict.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import pytorch_lightning as pl
4
+
5
+ from ldm.util import instantiate_from_config
6
+
7
+ from ldm.modules.diffusionmodules.model import Encoder, Decoder
8
+ from ldm.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
9
+
10
+
11
+ class VQModelDual(pl.LightningModule):
12
+ def __init__(self,
13
+ ddconfig,
14
+ lossconfig,
15
+ n_embed,
16
+ embed_dim,
17
+ ckpt_path=None,
18
+ ignore_keys=[],
19
+ image1_key="image1",
20
+ image2_key="image2",
21
+ colorize_nlabels=None,
22
+ monitor=None,
23
+ remap=None,
24
+ sane_index_shape=False, # tell vector quantizer to return indices as bhw
25
+ ):
26
+ super().__init__()
27
+ self.image1_key = image1_key
28
+ self.image2_key = image2_key
29
+
30
+ ## model 1
31
+ self.encoder1 = Encoder(**ddconfig)
32
+ self.decoder1 = Decoder(**ddconfig)
33
+ self.quantize1 = VectorQuantizer(n_embed, embed_dim, beta=0.25,
34
+ remap=remap, sane_index_shape=sane_index_shape)
35
+ self.quant_conv1= torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
36
+ self.post_quant_conv1 = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
37
+ self.loss1 = instantiate_from_config(lossconfig)
38
+
39
+ ## model 2
40
+ self.encoder2 = Encoder(**ddconfig)
41
+ self.decoder2 = Decoder(**ddconfig)
42
+ self.quantize2 = VectorQuantizer(n_embed, embed_dim, beta=0.25,
43
+ remap=remap, sane_index_shape=sane_index_shape)
44
+ self.quant_conv2 = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
45
+ self.post_quant_conv2 = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
46
+ self.loss2 = instantiate_from_config(lossconfig)
47
+
48
+
49
+ if ckpt_path is not None:
50
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
51
+
52
+ if colorize_nlabels is not None:
53
+ assert type(colorize_nlabels)==int
54
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
55
+ if monitor is not None:
56
+ self.monitor = monitor
57
+
58
+ def init_from_ckpt(self, path, ignore_keys=list()):
59
+ sd = torch.load(path, map_location="cpu")["state_dict"]
60
+ keys = list(sd.keys())
61
+ for k in keys:
62
+ for ik in ignore_keys:
63
+ if k.startswith(ik):
64
+ print("Deleting key {} from state_dict.".format(k))
65
+ del sd[k]
66
+ self.load_state_dict(sd, strict=False)
67
+ print(f"Restored from {path}")
68
+
69
+ def encode(self, x1, x2):
70
+ h1 = self.encoder1(x1)
71
+ h1 = self.quant_conv1(h1)
72
+ quant1, emb_loss1, info1 = self.quantize1(h1)
73
+ h2 = self.encoder2(x2)
74
+ h2 = self.quant_conv2(h2)
75
+ quant2, emb_loss2, info2 = self.quantize2(h2)
76
+ return quant1, emb_loss1, info1, quant2, emb_loss2, info2
77
+
78
+ def decode(self, quant1, quant2):
79
+ quant1 = self.post_quant_conv1(quant1)
80
+ dec1 = self.decoder1(quant1)
81
+ quant2 = self.post_quant_conv2(quant2)
82
+ dec2 = self.decoder2(quant2)
83
+ return dec1, dec2
84
+
85
+ # def decode_code(self, code_b, model_key):
86
+ # quant_b = self.quantize[model_key].embed_code(code_b)
87
+ # dec = self.decode(quant_b,model_key)
88
+ # return dec
89
+
90
+ def forward(self, input1, input2):
91
+ # quant, diff, _ = self.encode(input, model_key)
92
+ quant1, diff1, _, quant2, diff2, _ = self.encode(input1, input2)
93
+ dec1, dec2 = self.decode(quant1, quant2)
94
+ # dec = self.decode(quant, model_key)
95
+ return dec1, dec2, diff1, diff2
96
+
97
+ def get_input(self, batch, k):
98
+ x = batch[k]
99
+ if len(x.shape) == 3:
100
+ x = x[..., None]
101
+ # x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format)
102
+ x = x.to(memory_format=torch.contiguous_format)
103
+ return x.float()
104
+
105
+ def training_step(self, batch, batch_idx, optimizer_idx):
106
+ x1 = self.get_input(batch, self.image1_key)
107
+ x2 = self.get_input(batch, self.image2_key)
108
+ xrec1, xrec2, qloss1, qloss2 = self.forward(x1, x2)
109
+
110
+
111
+ if optimizer_idx == 0:
112
+ # autoencoder 1
113
+ aeloss1, log_dict_ae1 = self.loss1(qloss1, x1, xrec1, optimizer_idx, self.global_step,
114
+ last_layer=self.get_last_layer(model_key=1), split="train")
115
+
116
+ self.log("train/aeloss1", aeloss1, prog_bar=True, logger=True, on_step=True, on_epoch=True)
117
+ self.log_dict(log_dict_ae1, prog_bar=False, logger=True, on_step=True, on_epoch=True)
118
+
119
+ # autoencoder 2
120
+ aeloss2, log_dict_ae2 = self.loss2(qloss2, x2, xrec2, optimizer_idx, self.global_step,
121
+ last_layer=self.get_last_layer(model_key=2), split="train")
122
+
123
+ self.log("train/aeloss2", aeloss2, prog_bar=True, logger=True, on_step=True, on_epoch=True)
124
+ self.log_dict(log_dict_ae2, prog_bar=False, logger=True, on_step=True, on_epoch=True)
125
+
126
+ return aeloss1 + aeloss2
127
+
128
+ if optimizer_idx == 1:
129
+ # discriminator 1
130
+ discloss1, log_dict_disc1 = self.loss1(qloss1, x1, xrec1, optimizer_idx, self.global_step,
131
+ last_layer=self.get_last_layer(model_key=1), split="train")
132
+ self.log("train/discloss1", discloss1, prog_bar=True, logger=True, on_step=True, on_epoch=True)
133
+ self.log_dict(log_dict_disc1, prog_bar=False, logger=True, on_step=True, on_epoch=True)
134
+
135
+ # discriminator 2
136
+ discloss2, log_dict_disc2 = self.loss2(qloss2, x2, xrec2, optimizer_idx, self.global_step,
137
+ last_layer=self.get_last_layer(model_key=2), split="train")
138
+ self.log("train/discloss", discloss2, prog_bar=True, logger=True, on_step=True, on_epoch=True)
139
+ self.log_dict(log_dict_disc2, prog_bar=False, logger=True, on_step=True, on_epoch=True)
140
+
141
+ return discloss1 + discloss2
142
+
143
+ def validation_step(self, batch, batch_idx):
144
+
145
+ x1 = self.get_input(batch, self.image1_key)
146
+ x2 = self.get_input(batch, self.image2_key)
147
+ xrec1, xrec2, qloss1, qloss2 = self.forward(x1, x2)
148
+
149
+
150
+ aeloss1, log_dict_ae1 = self.loss1(qloss1, x1, xrec1, 0, self.global_step,
151
+ last_layer=self.get_last_layer(model_key=1), split="val")
152
+ aeloss2, log_dict_ae2 = self.loss2(qloss2, x2, xrec2, 0, self.global_step,
153
+ last_layer=self.get_last_layer(model_key=2), split="val")
154
+
155
+ discloss1, log_dict_disc1 = self.loss1(qloss1, x1, xrec1, 1, self.global_step,
156
+ last_layer=self.get_last_layer(model_key=1), split="val")
157
+ discloss2, log_dict_disc2 = self.loss2(qloss2, x2, xrec2, 1, self.global_step,
158
+ last_layer=self.get_last_layer(model_key=2), split="val")
159
+
160
+ rec_loss1 = log_dict_ae1["val/rec_loss"]
161
+ rec_loss2 = log_dict_ae2["val/rec_loss"]
162
+ self.log("val/rec_loss1", rec_loss1,
163
+ prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
164
+ self.log("val/rec_loss2", rec_loss2,
165
+ prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
166
+ self.log("val/aeloss1", aeloss1,
167
+ prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
168
+ self.log("val/aeloss2", aeloss2,
169
+ prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
170
+ self.log_dict(log_dict_ae1)
171
+ self.log_dict(log_dict_disc1)
172
+ self.log_dict(log_dict_ae2)
173
+ self.log_dict(log_dict_disc2)
174
+ return self.log_dict
175
+
176
+ def configure_optimizers(self):
177
+ lr = self.learning_rate
178
+ opt_ae = torch.optim.Adam(list(self.encoder1.parameters())+
179
+ list(self.decoder1.parameters())+
180
+ list(self.quantize1.parameters())+
181
+ list(self.quant_conv1.parameters())+
182
+ list(self.post_quant_conv1.parameters())+
183
+ list(self.encoder2.parameters())+
184
+ list(self.decoder2.parameters())+
185
+ list(self.quantize2.parameters())+
186
+ list(self.quant_conv2.parameters())+
187
+ list(self.post_quant_conv2.parameters()),
188
+ lr=lr, betas=(0.5, 0.9))
189
+ opt_disc = torch.optim.Adam(list(self.loss1.discriminator.parameters())+
190
+ list(self.loss2.discriminator.parameters()),
191
+ lr=lr, betas=(0.5, 0.9))
192
+ return [opt_ae, opt_disc], []
193
+
194
+ def get_last_layer(self, model_key):
195
+ if model_key==1:
196
+ return self.decoder2.conv_out.weight
197
+ elif model_key==2:
198
+ return self.decoder2.conv_out.weight
199
+
200
+ def log_images(self, batch, **kwargs):
201
+ log = dict()
202
+
203
+
204
+ x1 = self.get_input(batch, self.image1_key)
205
+ x2 = self.get_input(batch, self.image2_key)
206
+ x1 = x1.to(self.device)
207
+ x2 = x2.to(self.device)
208
+
209
+ xrec1, xrec2, _, _ = self.forward(x1, x2)
210
+
211
+ ## log 1
212
+ if x1.shape[1] > 3:
213
+ # colorize with random projection
214
+ assert xrec1.shape[1] > 3
215
+ x1 = self.to_rgb(x1)
216
+ xrec1 = self.to_rgb(xrec1)
217
+ log["inputs1"] = x1
218
+ log["reconstructions1"] = xrec1
219
+
220
+
221
+ ## log 2
222
+ if x2.shape[1] > 3:
223
+ # colorize with random projection
224
+ assert xrec2.shape[1] > 3
225
+ x2 = self.to_rgb(x2)
226
+ xrec2 = self.to_rgb(xrec2)
227
+ log["inputs2"] = x2
228
+ log["reconstructions2"] = xrec2
229
+ return log
230
+
231
+ def to_rgb(self, x):
232
+ assert self.image_key == "segmentation"
233
+ if not hasattr(self, "colorize"):
234
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
235
+ x = F.conv2d(x, weight=self.colorize)
236
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
237
+ return x
238
+
239
+ class VQModelDualInterface(VQModelDual):
240
+ def __init__(self, embed_dim, *args, **kwargs):
241
+ super().__init__(embed_dim=embed_dim, *args, **kwargs)
242
+ self.embed_dim = embed_dim
243
+
244
+ def encode(self, x1, x2):
245
+
246
+ h1 = self.encoder1(x1)
247
+ h1 = self.quant_conv1(h1)
248
+
249
+ h2 = self.encoder2(x2)
250
+ h2 = self.quant_conv2(h2)
251
+
252
+ return h1, h2
253
+
254
+ def decode(self, h1, h2, force_not_quantize=False):
255
+ # also go through quantization layer
256
+ if not force_not_quantize:
257
+ quant1, emb_loss1, info1 = self.quantize1(h1)
258
+ quant2, emb_loss2, info2 = self.quantize2(h2)
259
+ else:
260
+ quant1 = h1
261
+ quant2 = h2
262
+
263
+ quant1 = self.post_quant_conv1(quant1)
264
+ dec1 = self.decoder1(quant1)
265
+
266
+ quant2 = self.post_quant_conv2(quant2)
267
+ dec2 = self.decoder2(quant2)
268
+
269
+ return dec1, dec2
270
+
271
+ def decode1(self, h1, force_not_quantize=False):
272
+ # also go through quantization layer
273
+ if not force_not_quantize:
274
+ quant1, emb_loss1, info1 = self.quantize1(h1)
275
+ else:
276
+ quant1 = h1
277
+ quant1 = self.post_quant_conv1(quant1)
278
+ dec1 = self.decoder1(quant1)
279
+ return dec1
280
+
281
+ def decode2(self, h2, force_not_quantize=False):
282
+ # also go through quantization layer
283
+ if not force_not_quantize:
284
+ quant2, emb_loss2, info2 = self.quantize2(h2)
285
+ else:
286
+ quant2 = h2
287
+ quant2 = self.post_quant_conv2(quant2)
288
+ dec2 = self.decoder2(quant2)
289
+ return dec2