Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
AUTOMATIC1111
GitHub Repository: AUTOMATIC1111/stable-diffusion-webui
Path: blob/master/extensions-builtin/LDSR/sd_hijack_autoencoder.py
2447 views
1
# The content of this file comes from the ldm/models/autoencoder.py file of the compvis/stable-diffusion repo
2
# The VQModel & VQModelInterface were subsequently removed from ldm/models/autoencoder.py when we moved to the stability-ai/stablediffusion repo
3
# As the LDSR upscaler relies on VQModel & VQModelInterface, the hijack aims to put them back into the ldm.models.autoencoder
4
import numpy as np
5
import torch
6
import pytorch_lightning as pl
7
import torch.nn.functional as F
8
from contextlib import contextmanager
9
10
from torch.optim.lr_scheduler import LambdaLR
11
12
from ldm.modules.ema import LitEma
13
from vqvae_quantize import VectorQuantizer2 as VectorQuantizer
14
from ldm.modules.diffusionmodules.model import Encoder, Decoder
15
from ldm.util import instantiate_from_config
16
17
import ldm.models.autoencoder
18
from packaging import version
19
20
class VQModel(pl.LightningModule):
21
def __init__(self,
22
ddconfig,
23
lossconfig,
24
n_embed,
25
embed_dim,
26
ckpt_path=None,
27
ignore_keys=None,
28
image_key="image",
29
colorize_nlabels=None,
30
monitor=None,
31
batch_resize_range=None,
32
scheduler_config=None,
33
lr_g_factor=1.0,
34
remap=None,
35
sane_index_shape=False, # tell vector quantizer to return indices as bhw
36
use_ema=False
37
):
38
super().__init__()
39
self.embed_dim = embed_dim
40
self.n_embed = n_embed
41
self.image_key = image_key
42
self.encoder = Encoder(**ddconfig)
43
self.decoder = Decoder(**ddconfig)
44
self.loss = instantiate_from_config(lossconfig)
45
self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25,
46
remap=remap,
47
sane_index_shape=sane_index_shape)
48
self.quant_conv = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
49
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
50
if colorize_nlabels is not None:
51
assert type(colorize_nlabels)==int
52
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
53
if monitor is not None:
54
self.monitor = monitor
55
self.batch_resize_range = batch_resize_range
56
if self.batch_resize_range is not None:
57
print(f"{self.__class__.__name__}: Using per-batch resizing in range {batch_resize_range}.")
58
59
self.use_ema = use_ema
60
if self.use_ema:
61
self.model_ema = LitEma(self)
62
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
63
64
if ckpt_path is not None:
65
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys or [])
66
self.scheduler_config = scheduler_config
67
self.lr_g_factor = lr_g_factor
68
69
@contextmanager
70
def ema_scope(self, context=None):
71
if self.use_ema:
72
self.model_ema.store(self.parameters())
73
self.model_ema.copy_to(self)
74
if context is not None:
75
print(f"{context}: Switched to EMA weights")
76
try:
77
yield None
78
finally:
79
if self.use_ema:
80
self.model_ema.restore(self.parameters())
81
if context is not None:
82
print(f"{context}: Restored training weights")
83
84
def init_from_ckpt(self, path, ignore_keys=None):
85
sd = torch.load(path, map_location="cpu")["state_dict"]
86
keys = list(sd.keys())
87
for k in keys:
88
for ik in ignore_keys or []:
89
if k.startswith(ik):
90
print("Deleting key {} from state_dict.".format(k))
91
del sd[k]
92
missing, unexpected = self.load_state_dict(sd, strict=False)
93
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
94
if missing:
95
print(f"Missing Keys: {missing}")
96
if unexpected:
97
print(f"Unexpected Keys: {unexpected}")
98
99
def on_train_batch_end(self, *args, **kwargs):
100
if self.use_ema:
101
self.model_ema(self)
102
103
def encode(self, x):
104
h = self.encoder(x)
105
h = self.quant_conv(h)
106
quant, emb_loss, info = self.quantize(h)
107
return quant, emb_loss, info
108
109
def encode_to_prequant(self, x):
110
h = self.encoder(x)
111
h = self.quant_conv(h)
112
return h
113
114
def decode(self, quant):
115
quant = self.post_quant_conv(quant)
116
dec = self.decoder(quant)
117
return dec
118
119
def decode_code(self, code_b):
120
quant_b = self.quantize.embed_code(code_b)
121
dec = self.decode(quant_b)
122
return dec
123
124
def forward(self, input, return_pred_indices=False):
125
quant, diff, (_,_,ind) = self.encode(input)
126
dec = self.decode(quant)
127
if return_pred_indices:
128
return dec, diff, ind
129
return dec, diff
130
131
def get_input(self, batch, k):
132
x = batch[k]
133
if len(x.shape) == 3:
134
x = x[..., None]
135
x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
136
if self.batch_resize_range is not None:
137
lower_size = self.batch_resize_range[0]
138
upper_size = self.batch_resize_range[1]
139
if self.global_step <= 4:
140
# do the first few batches with max size to avoid later oom
141
new_resize = upper_size
142
else:
143
new_resize = np.random.choice(np.arange(lower_size, upper_size+16, 16))
144
if new_resize != x.shape[2]:
145
x = F.interpolate(x, size=new_resize, mode="bicubic")
146
x = x.detach()
147
return x
148
149
def training_step(self, batch, batch_idx, optimizer_idx):
150
# https://github.com/pytorch/pytorch/issues/37142
151
# try not to fool the heuristics
152
x = self.get_input(batch, self.image_key)
153
xrec, qloss, ind = self(x, return_pred_indices=True)
154
155
if optimizer_idx == 0:
156
# autoencode
157
aeloss, log_dict_ae = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
158
last_layer=self.get_last_layer(), split="train",
159
predicted_indices=ind)
160
161
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
162
return aeloss
163
164
if optimizer_idx == 1:
165
# discriminator
166
discloss, log_dict_disc = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
167
last_layer=self.get_last_layer(), split="train")
168
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True)
169
return discloss
170
171
def validation_step(self, batch, batch_idx):
172
log_dict = self._validation_step(batch, batch_idx)
173
with self.ema_scope():
174
self._validation_step(batch, batch_idx, suffix="_ema")
175
return log_dict
176
177
def _validation_step(self, batch, batch_idx, suffix=""):
178
x = self.get_input(batch, self.image_key)
179
xrec, qloss, ind = self(x, return_pred_indices=True)
180
aeloss, log_dict_ae = self.loss(qloss, x, xrec, 0,
181
self.global_step,
182
last_layer=self.get_last_layer(),
183
split="val"+suffix,
184
predicted_indices=ind
185
)
186
187
discloss, log_dict_disc = self.loss(qloss, x, xrec, 1,
188
self.global_step,
189
last_layer=self.get_last_layer(),
190
split="val"+suffix,
191
predicted_indices=ind
192
)
193
rec_loss = log_dict_ae[f"val{suffix}/rec_loss"]
194
self.log(f"val{suffix}/rec_loss", rec_loss,
195
prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
196
self.log(f"val{suffix}/aeloss", aeloss,
197
prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
198
if version.parse(pl.__version__) >= version.parse('1.4.0'):
199
del log_dict_ae[f"val{suffix}/rec_loss"]
200
self.log_dict(log_dict_ae)
201
self.log_dict(log_dict_disc)
202
return self.log_dict
203
204
def configure_optimizers(self):
205
lr_d = self.learning_rate
206
lr_g = self.lr_g_factor*self.learning_rate
207
print("lr_d", lr_d)
208
print("lr_g", lr_g)
209
opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
210
list(self.decoder.parameters())+
211
list(self.quantize.parameters())+
212
list(self.quant_conv.parameters())+
213
list(self.post_quant_conv.parameters()),
214
lr=lr_g, betas=(0.5, 0.9))
215
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
216
lr=lr_d, betas=(0.5, 0.9))
217
218
if self.scheduler_config is not None:
219
scheduler = instantiate_from_config(self.scheduler_config)
220
221
print("Setting up LambdaLR scheduler...")
222
scheduler = [
223
{
224
'scheduler': LambdaLR(opt_ae, lr_lambda=scheduler.schedule),
225
'interval': 'step',
226
'frequency': 1
227
},
228
{
229
'scheduler': LambdaLR(opt_disc, lr_lambda=scheduler.schedule),
230
'interval': 'step',
231
'frequency': 1
232
},
233
]
234
return [opt_ae, opt_disc], scheduler
235
return [opt_ae, opt_disc], []
236
237
def get_last_layer(self):
238
return self.decoder.conv_out.weight
239
240
def log_images(self, batch, only_inputs=False, plot_ema=False, **kwargs):
241
log = {}
242
x = self.get_input(batch, self.image_key)
243
x = x.to(self.device)
244
if only_inputs:
245
log["inputs"] = x
246
return log
247
xrec, _ = self(x)
248
if x.shape[1] > 3:
249
# colorize with random projection
250
assert xrec.shape[1] > 3
251
x = self.to_rgb(x)
252
xrec = self.to_rgb(xrec)
253
log["inputs"] = x
254
log["reconstructions"] = xrec
255
if plot_ema:
256
with self.ema_scope():
257
xrec_ema, _ = self(x)
258
if x.shape[1] > 3:
259
xrec_ema = self.to_rgb(xrec_ema)
260
log["reconstructions_ema"] = xrec_ema
261
return log
262
263
def to_rgb(self, x):
264
assert self.image_key == "segmentation"
265
if not hasattr(self, "colorize"):
266
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
267
x = F.conv2d(x, weight=self.colorize)
268
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
269
return x
270
271
272
class VQModelInterface(VQModel):
273
def __init__(self, embed_dim, *args, **kwargs):
274
super().__init__(*args, embed_dim=embed_dim, **kwargs)
275
self.embed_dim = embed_dim
276
277
def encode(self, x):
278
h = self.encoder(x)
279
h = self.quant_conv(h)
280
return h
281
282
def decode(self, h, force_not_quantize=False):
283
# also go through quantization layer
284
if not force_not_quantize:
285
quant, emb_loss, info = self.quantize(h)
286
else:
287
quant = h
288
quant = self.post_quant_conv(quant)
289
dec = self.decoder(quant)
290
return dec
291
292
ldm.models.autoencoder.VQModel = VQModel
293
ldm.models.autoencoder.VQModelInterface = VQModelInterface
294
295