Fabrice-TIERCELIN commited on
Commit
e3b586a
·
verified ·
1 Parent(s): 7401785

Delete sgm

Browse files
Files changed (39) hide show
  1. sgm/__init__.py +0 -4
  2. sgm/lr_scheduler.py +0 -135
  3. sgm/models/__init__.py +0 -2
  4. sgm/models/autoencoder.py +0 -335
  5. sgm/models/diffusion.py +0 -320
  6. sgm/modules/__init__.py +0 -8
  7. sgm/modules/attention.py +0 -635
  8. sgm/modules/autoencoding/__init__.py +0 -0
  9. sgm/modules/autoencoding/losses/__init__.py +0 -246
  10. sgm/modules/autoencoding/lpips/__init__.py +0 -0
  11. sgm/modules/autoencoding/lpips/loss/LICENSE +0 -23
  12. sgm/modules/autoencoding/lpips/loss/__init__.py +0 -0
  13. sgm/modules/autoencoding/lpips/loss/lpips.py +0 -147
  14. sgm/modules/autoencoding/lpips/model/LICENSE +0 -58
  15. sgm/modules/autoencoding/lpips/model/__init__.py +0 -0
  16. sgm/modules/autoencoding/lpips/model/model.py +0 -88
  17. sgm/modules/autoencoding/lpips/util.py +0 -128
  18. sgm/modules/autoencoding/lpips/vqperceptual.py +0 -17
  19. sgm/modules/autoencoding/regularizers/__init__.py +0 -53
  20. sgm/modules/diffusionmodules/__init__.py +0 -7
  21. sgm/modules/diffusionmodules/denoiser.py +0 -73
  22. sgm/modules/diffusionmodules/denoiser_scaling.py +0 -31
  23. sgm/modules/diffusionmodules/denoiser_weighting.py +0 -24
  24. sgm/modules/diffusionmodules/discretizer.py +0 -69
  25. sgm/modules/diffusionmodules/guiders.py +0 -88
  26. sgm/modules/diffusionmodules/loss.py +0 -69
  27. sgm/modules/diffusionmodules/model.py +0 -743
  28. sgm/modules/diffusionmodules/openaimodel.py +0 -1272
  29. sgm/modules/diffusionmodules/sampling.py +0 -766
  30. sgm/modules/diffusionmodules/sampling_utils.py +0 -48
  31. sgm/modules/diffusionmodules/sigma_sampling.py +0 -40
  32. sgm/modules/diffusionmodules/util.py +0 -309
  33. sgm/modules/diffusionmodules/wrappers.py +0 -103
  34. sgm/modules/distributions/__init__.py +0 -0
  35. sgm/modules/distributions/distributions.py +0 -102
  36. sgm/modules/ema.py +0 -86
  37. sgm/modules/encoders/__init__.py +0 -0
  38. sgm/modules/encoders/modules.py +0 -1062
  39. sgm/util.py +0 -248
sgm/__init__.py DELETED
@@ -1,4 +0,0 @@
1
- from .models import AutoencodingEngine, DiffusionEngine
2
- from .util import get_configs_path, instantiate_from_config
3
-
4
- __version__ = "0.1.0"
 
 
 
 
 
sgm/lr_scheduler.py DELETED
@@ -1,135 +0,0 @@
1
- import numpy as np
2
-
3
-
4
- class LambdaWarmUpCosineScheduler:
5
- """
6
- note: use with a base_lr of 1.0
7
- """
8
-
9
- def __init__(
10
- self,
11
- warm_up_steps,
12
- lr_min,
13
- lr_max,
14
- lr_start,
15
- max_decay_steps,
16
- verbosity_interval=0,
17
- ):
18
- self.lr_warm_up_steps = warm_up_steps
19
- self.lr_start = lr_start
20
- self.lr_min = lr_min
21
- self.lr_max = lr_max
22
- self.lr_max_decay_steps = max_decay_steps
23
- self.last_lr = 0.0
24
- self.verbosity_interval = verbosity_interval
25
-
26
- def schedule(self, n, **kwargs):
27
- if self.verbosity_interval > 0:
28
- if n % self.verbosity_interval == 0:
29
- print(f"current step: {n}, recent lr-multiplier: {self.last_lr}")
30
- if n < self.lr_warm_up_steps:
31
- lr = (
32
- self.lr_max - self.lr_start
33
- ) / self.lr_warm_up_steps * n + self.lr_start
34
- self.last_lr = lr
35
- return lr
36
- else:
37
- t = (n - self.lr_warm_up_steps) / (
38
- self.lr_max_decay_steps - self.lr_warm_up_steps
39
- )
40
- t = min(t, 1.0)
41
- lr = self.lr_min + 0.5 * (self.lr_max - self.lr_min) * (
42
- 1 + np.cos(t * np.pi)
43
- )
44
- self.last_lr = lr
45
- return lr
46
-
47
- def __call__(self, n, **kwargs):
48
- return self.schedule(n, **kwargs)
49
-
50
-
51
- class LambdaWarmUpCosineScheduler2:
52
- """
53
- supports repeated iterations, configurable via lists
54
- note: use with a base_lr of 1.0.
55
- """
56
-
57
- def __init__(
58
- self, warm_up_steps, f_min, f_max, f_start, cycle_lengths, verbosity_interval=0
59
- ):
60
- assert (
61
- len(warm_up_steps)
62
- == len(f_min)
63
- == len(f_max)
64
- == len(f_start)
65
- == len(cycle_lengths)
66
- )
67
- self.lr_warm_up_steps = warm_up_steps
68
- self.f_start = f_start
69
- self.f_min = f_min
70
- self.f_max = f_max
71
- self.cycle_lengths = cycle_lengths
72
- self.cum_cycles = np.cumsum([0] + list(self.cycle_lengths))
73
- self.last_f = 0.0
74
- self.verbosity_interval = verbosity_interval
75
-
76
- def find_in_interval(self, n):
77
- interval = 0
78
- for cl in self.cum_cycles[1:]:
79
- if n <= cl:
80
- return interval
81
- interval += 1
82
-
83
- def schedule(self, n, **kwargs):
84
- cycle = self.find_in_interval(n)
85
- n = n - self.cum_cycles[cycle]
86
- if self.verbosity_interval > 0:
87
- if n % self.verbosity_interval == 0:
88
- print(
89
- f"current step: {n}, recent lr-multiplier: {self.last_f}, "
90
- f"current cycle {cycle}"
91
- )
92
- if n < self.lr_warm_up_steps[cycle]:
93
- f = (self.f_max[cycle] - self.f_start[cycle]) / self.lr_warm_up_steps[
94
- cycle
95
- ] * n + self.f_start[cycle]
96
- self.last_f = f
97
- return f
98
- else:
99
- t = (n - self.lr_warm_up_steps[cycle]) / (
100
- self.cycle_lengths[cycle] - self.lr_warm_up_steps[cycle]
101
- )
102
- t = min(t, 1.0)
103
- f = self.f_min[cycle] + 0.5 * (self.f_max[cycle] - self.f_min[cycle]) * (
104
- 1 + np.cos(t * np.pi)
105
- )
106
- self.last_f = f
107
- return f
108
-
109
- def __call__(self, n, **kwargs):
110
- return self.schedule(n, **kwargs)
111
-
112
-
113
- class LambdaLinearScheduler(LambdaWarmUpCosineScheduler2):
114
- def schedule(self, n, **kwargs):
115
- cycle = self.find_in_interval(n)
116
- n = n - self.cum_cycles[cycle]
117
- if self.verbosity_interval > 0:
118
- if n % self.verbosity_interval == 0:
119
- print(
120
- f"current step: {n}, recent lr-multiplier: {self.last_f}, "
121
- f"current cycle {cycle}"
122
- )
123
-
124
- if n < self.lr_warm_up_steps[cycle]:
125
- f = (self.f_max[cycle] - self.f_start[cycle]) / self.lr_warm_up_steps[
126
- cycle
127
- ] * n + self.f_start[cycle]
128
- self.last_f = f
129
- return f
130
- else:
131
- f = self.f_min[cycle] + (self.f_max[cycle] - self.f_min[cycle]) * (
132
- self.cycle_lengths[cycle] - n
133
- ) / (self.cycle_lengths[cycle])
134
- self.last_f = f
135
- return f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/models/__init__.py DELETED
@@ -1,2 +0,0 @@
1
- from .autoencoder import AutoencodingEngine
2
- from .diffusion import DiffusionEngine
 
 
 
sgm/models/autoencoder.py DELETED
@@ -1,335 +0,0 @@
1
- import re
2
- from abc import abstractmethod
3
- from contextlib import contextmanager
4
- from typing import Any, Dict, Tuple, Union
5
-
6
- import pytorch_lightning as pl
7
- import torch
8
- from omegaconf import ListConfig
9
- from packaging import version
10
- from safetensors.torch import load_file as load_safetensors
11
-
12
- from ..modules.diffusionmodules.model import Decoder, Encoder
13
- from ..modules.distributions.distributions import DiagonalGaussianDistribution
14
- from ..modules.ema import LitEma
15
- from ..util import default, get_obj_from_str, instantiate_from_config
16
-
17
-
18
- class AbstractAutoencoder(pl.LightningModule):
19
- """
20
- This is the base class for all autoencoders, including image autoencoders, image autoencoders with discriminators,
21
- unCLIP models, etc. Hence, it is fairly general, and specific features
22
- (e.g. discriminator training, encoding, decoding) must be implemented in subclasses.
23
- """
24
-
25
- def __init__(
26
- self,
27
- ema_decay: Union[None, float] = None,
28
- monitor: Union[None, str] = None,
29
- input_key: str = "jpg",
30
- ckpt_path: Union[None, str] = None,
31
- ignore_keys: Union[Tuple, list, ListConfig] = (),
32
- ):
33
- super().__init__()
34
- self.input_key = input_key
35
- self.use_ema = ema_decay is not None
36
- if monitor is not None:
37
- self.monitor = monitor
38
-
39
- if self.use_ema:
40
- self.model_ema = LitEma(self, decay=ema_decay)
41
- print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
42
-
43
- if ckpt_path is not None:
44
- self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
45
-
46
- if version.parse(torch.__version__) >= version.parse("2.0.0"):
47
- self.automatic_optimization = False
48
-
49
- def init_from_ckpt(
50
- self, path: str, ignore_keys: Union[Tuple, list, ListConfig] = tuple()
51
- ) -> None:
52
- if path.endswith("ckpt"):
53
- sd = torch.load(path, map_location="cpu")["state_dict"]
54
- elif path.endswith("safetensors"):
55
- sd = load_safetensors(path)
56
- else:
57
- raise NotImplementedError
58
-
59
- keys = list(sd.keys())
60
- for k in keys:
61
- for ik in ignore_keys:
62
- if re.match(ik, k):
63
- print("Deleting key {} from state_dict.".format(k))
64
- del sd[k]
65
- missing, unexpected = self.load_state_dict(sd, strict=False)
66
- print(
67
- f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys"
68
- )
69
- if len(missing) > 0:
70
- print(f"Missing Keys: {missing}")
71
- if len(unexpected) > 0:
72
- print(f"Unexpected Keys: {unexpected}")
73
-
74
- @abstractmethod
75
- def get_input(self, batch) -> Any:
76
- raise NotImplementedError()
77
-
78
- def on_train_batch_end(self, *args, **kwargs):
79
- # for EMA computation
80
- if self.use_ema:
81
- self.model_ema(self)
82
-
83
- @contextmanager
84
- def ema_scope(self, context=None):
85
- if self.use_ema:
86
- self.model_ema.store(self.parameters())
87
- self.model_ema.copy_to(self)
88
- if context is not None:
89
- print(f"{context}: Switched to EMA weights")
90
- try:
91
- yield None
92
- finally:
93
- if self.use_ema:
94
- self.model_ema.restore(self.parameters())
95
- if context is not None:
96
- print(f"{context}: Restored training weights")
97
-
98
- @abstractmethod
99
- def encode(self, *args, **kwargs) -> torch.Tensor:
100
- raise NotImplementedError("encode()-method of abstract base class called")
101
-
102
- @abstractmethod
103
- def decode(self, *args, **kwargs) -> torch.Tensor:
104
- raise NotImplementedError("decode()-method of abstract base class called")
105
-
106
- def instantiate_optimizer_from_config(self, params, lr, cfg):
107
- print(f"loading >>> {cfg['target']} <<< optimizer from config")
108
- return get_obj_from_str(cfg["target"])(
109
- params, lr=lr, **cfg.get("params", dict())
110
- )
111
-
112
- def configure_optimizers(self) -> Any:
113
- raise NotImplementedError()
114
-
115
-
116
- class AutoencodingEngine(AbstractAutoencoder):
117
- """
118
- Base class for all image autoencoders that we train, like VQGAN or AutoencoderKL
119
- (we also restore them explicitly as special cases for legacy reasons).
120
- Regularizations such as KL or VQ are moved to the regularizer class.
121
- """
122
-
123
- def __init__(
124
- self,
125
- *args,
126
- encoder_config: Dict,
127
- decoder_config: Dict,
128
- loss_config: Dict,
129
- regularizer_config: Dict,
130
- optimizer_config: Union[Dict, None] = None,
131
- lr_g_factor: float = 1.0,
132
- **kwargs,
133
- ):
134
- super().__init__(*args, **kwargs)
135
- # todo: add options to freeze encoder/decoder
136
- self.encoder = instantiate_from_config(encoder_config)
137
- self.decoder = instantiate_from_config(decoder_config)
138
- self.loss = instantiate_from_config(loss_config)
139
- self.regularization = instantiate_from_config(regularizer_config)
140
- self.optimizer_config = default(
141
- optimizer_config, {"target": "torch.optim.Adam"}
142
- )
143
- self.lr_g_factor = lr_g_factor
144
-
145
- def get_input(self, batch: Dict) -> torch.Tensor:
146
- # assuming unified data format, dataloader returns a dict.
147
- # image tensors should be scaled to -1 ... 1 and in channels-first format (e.g., bchw instead if bhwc)
148
- return batch[self.input_key]
149
-
150
- def get_autoencoder_params(self) -> list:
151
- params = (
152
- list(self.encoder.parameters())
153
- + list(self.decoder.parameters())
154
- + list(self.regularization.get_trainable_parameters())
155
- + list(self.loss.get_trainable_autoencoder_parameters())
156
- )
157
- return params
158
-
159
- def get_discriminator_params(self) -> list:
160
- params = list(self.loss.get_trainable_parameters()) # e.g., discriminator
161
- return params
162
-
163
- def get_last_layer(self):
164
- return self.decoder.get_last_layer()
165
-
166
- def encode(self, x: Any, return_reg_log: bool = False) -> Any:
167
- z = self.encoder(x)
168
- z, reg_log = self.regularization(z)
169
- if return_reg_log:
170
- return z, reg_log
171
- return z
172
-
173
- def decode(self, z: Any) -> torch.Tensor:
174
- x = self.decoder(z)
175
- return x
176
-
177
- def forward(self, x: Any) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
178
- z, reg_log = self.encode(x, return_reg_log=True)
179
- dec = self.decode(z)
180
- return z, dec, reg_log
181
-
182
- def training_step(self, batch, batch_idx, optimizer_idx) -> Any:
183
- x = self.get_input(batch)
184
- z, xrec, regularization_log = self(x)
185
-
186
- if optimizer_idx == 0:
187
- # autoencode
188
- aeloss, log_dict_ae = self.loss(
189
- regularization_log,
190
- x,
191
- xrec,
192
- optimizer_idx,
193
- self.global_step,
194
- last_layer=self.get_last_layer(),
195
- split="train",
196
- )
197
-
198
- self.log_dict(
199
- log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True
200
- )
201
- return aeloss
202
-
203
- if optimizer_idx == 1:
204
- # discriminator
205
- discloss, log_dict_disc = self.loss(
206
- regularization_log,
207
- x,
208
- xrec,
209
- optimizer_idx,
210
- self.global_step,
211
- last_layer=self.get_last_layer(),
212
- split="train",
213
- )
214
- self.log_dict(
215
- log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True
216
- )
217
- return discloss
218
-
219
- def validation_step(self, batch, batch_idx) -> Dict:
220
- log_dict = self._validation_step(batch, batch_idx)
221
- with self.ema_scope():
222
- log_dict_ema = self._validation_step(batch, batch_idx, postfix="_ema")
223
- log_dict.update(log_dict_ema)
224
- return log_dict
225
-
226
- def _validation_step(self, batch, batch_idx, postfix="") -> Dict:
227
- x = self.get_input(batch)
228
-
229
- z, xrec, regularization_log = self(x)
230
- aeloss, log_dict_ae = self.loss(
231
- regularization_log,
232
- x,
233
- xrec,
234
- 0,
235
- self.global_step,
236
- last_layer=self.get_last_layer(),
237
- split="val" + postfix,
238
- )
239
-
240
- discloss, log_dict_disc = self.loss(
241
- regularization_log,
242
- x,
243
- xrec,
244
- 1,
245
- self.global_step,
246
- last_layer=self.get_last_layer(),
247
- split="val" + postfix,
248
- )
249
- self.log(f"val{postfix}/rec_loss", log_dict_ae[f"val{postfix}/rec_loss"])
250
- log_dict_ae.update(log_dict_disc)
251
- self.log_dict(log_dict_ae)
252
- return log_dict_ae
253
-
254
- def configure_optimizers(self) -> Any:
255
- ae_params = self.get_autoencoder_params()
256
- disc_params = self.get_discriminator_params()
257
-
258
- opt_ae = self.instantiate_optimizer_from_config(
259
- ae_params,
260
- default(self.lr_g_factor, 1.0) * self.learning_rate,
261
- self.optimizer_config,
262
- )
263
- opt_disc = self.instantiate_optimizer_from_config(
264
- disc_params, self.learning_rate, self.optimizer_config
265
- )
266
-
267
- return [opt_ae, opt_disc], []
268
-
269
- @torch.no_grad()
270
- def log_images(self, batch: Dict, **kwargs) -> Dict:
271
- log = dict()
272
- x = self.get_input(batch)
273
- _, xrec, _ = self(x)
274
- log["inputs"] = x
275
- log["reconstructions"] = xrec
276
- with self.ema_scope():
277
- _, xrec_ema, _ = self(x)
278
- log["reconstructions_ema"] = xrec_ema
279
- return log
280
-
281
-
282
- class AutoencoderKL(AutoencodingEngine):
283
- def __init__(self, embed_dim: int, **kwargs):
284
- ddconfig = kwargs.pop("ddconfig")
285
- ckpt_path = kwargs.pop("ckpt_path", None)
286
- ignore_keys = kwargs.pop("ignore_keys", ())
287
- super().__init__(
288
- encoder_config={"target": "torch.nn.Identity"},
289
- decoder_config={"target": "torch.nn.Identity"},
290
- regularizer_config={"target": "torch.nn.Identity"},
291
- loss_config=kwargs.pop("lossconfig"),
292
- **kwargs,
293
- )
294
- assert ddconfig["double_z"]
295
- self.encoder = Encoder(**ddconfig)
296
- self.decoder = Decoder(**ddconfig)
297
- self.quant_conv = torch.nn.Conv2d(2 * ddconfig["z_channels"], 2 * embed_dim, 1)
298
- self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
299
- self.embed_dim = embed_dim
300
-
301
- if ckpt_path is not None:
302
- self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
303
-
304
- def encode(self, x):
305
- assert (
306
- not self.training
307
- ), f"{self.__class__.__name__} only supports inference currently"
308
- h = self.encoder(x)
309
- moments = self.quant_conv(h)
310
- posterior = DiagonalGaussianDistribution(moments)
311
- return posterior
312
-
313
- def decode(self, z, **decoder_kwargs):
314
- z = self.post_quant_conv(z)
315
- dec = self.decoder(z, **decoder_kwargs)
316
- return dec
317
-
318
-
319
- class AutoencoderKLInferenceWrapper(AutoencoderKL):
320
- def encode(self, x):
321
- return super().encode(x).sample()
322
-
323
-
324
- class IdentityFirstStage(AbstractAutoencoder):
325
- def __init__(self, *args, **kwargs):
326
- super().__init__(*args, **kwargs)
327
-
328
- def get_input(self, x: Any) -> Any:
329
- return x
330
-
331
- def encode(self, x: Any, *args, **kwargs) -> Any:
332
- return x
333
-
334
- def decode(self, x: Any, *args, **kwargs) -> Any:
335
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/models/diffusion.py DELETED
@@ -1,320 +0,0 @@
1
- from contextlib import contextmanager
2
- from typing import Any, Dict, List, Tuple, Union
3
-
4
- import pytorch_lightning as pl
5
- import torch
6
- from omegaconf import ListConfig, OmegaConf
7
- from safetensors.torch import load_file as load_safetensors
8
- from torch.optim.lr_scheduler import LambdaLR
9
-
10
- from ..modules import UNCONDITIONAL_CONFIG
11
- from ..modules.diffusionmodules.wrappers import OPENAIUNETWRAPPER
12
- from ..modules.ema import LitEma
13
- from ..util import (
14
- default,
15
- disabled_train,
16
- get_obj_from_str,
17
- instantiate_from_config,
18
- log_txt_as_img,
19
- )
20
-
21
-
22
- class DiffusionEngine(pl.LightningModule):
23
- def __init__(
24
- self,
25
- network_config,
26
- denoiser_config,
27
- first_stage_config,
28
- conditioner_config: Union[None, Dict, ListConfig, OmegaConf] = None,
29
- sampler_config: Union[None, Dict, ListConfig, OmegaConf] = None,
30
- optimizer_config: Union[None, Dict, ListConfig, OmegaConf] = None,
31
- scheduler_config: Union[None, Dict, ListConfig, OmegaConf] = None,
32
- loss_fn_config: Union[None, Dict, ListConfig, OmegaConf] = None,
33
- network_wrapper: Union[None, str] = None,
34
- ckpt_path: Union[None, str] = None,
35
- use_ema: bool = False,
36
- ema_decay_rate: float = 0.9999,
37
- scale_factor: float = 1.0,
38
- disable_first_stage_autocast=False,
39
- input_key: str = "jpg",
40
- log_keys: Union[List, None] = None,
41
- no_cond_log: bool = False,
42
- compile_model: bool = False,
43
- ):
44
- super().__init__()
45
- self.log_keys = log_keys
46
- self.input_key = input_key
47
- self.optimizer_config = default(
48
- optimizer_config, {"target": "torch.optim.AdamW"}
49
- )
50
- model = instantiate_from_config(network_config)
51
- self.model = get_obj_from_str(default(network_wrapper, OPENAIUNETWRAPPER))(
52
- model, compile_model=compile_model
53
- )
54
-
55
- self.denoiser = instantiate_from_config(denoiser_config)
56
- self.sampler = (
57
- instantiate_from_config(sampler_config)
58
- if sampler_config is not None
59
- else None
60
- )
61
- self.conditioner = instantiate_from_config(
62
- default(conditioner_config, UNCONDITIONAL_CONFIG)
63
- )
64
- self.scheduler_config = scheduler_config
65
- self._init_first_stage(first_stage_config)
66
-
67
- self.loss_fn = (
68
- instantiate_from_config(loss_fn_config)
69
- if loss_fn_config is not None
70
- else None
71
- )
72
-
73
- self.use_ema = use_ema
74
- if self.use_ema:
75
- self.model_ema = LitEma(self.model, decay=ema_decay_rate)
76
- print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
77
-
78
- self.scale_factor = scale_factor
79
- self.disable_first_stage_autocast = disable_first_stage_autocast
80
- self.no_cond_log = no_cond_log
81
-
82
- if ckpt_path is not None:
83
- self.init_from_ckpt(ckpt_path)
84
-
85
- def init_from_ckpt(
86
- self,
87
- path: str,
88
- ) -> None:
89
- if path.endswith("ckpt"):
90
- sd = torch.load(path, map_location="cpu")["state_dict"]
91
- elif path.endswith("safetensors"):
92
- sd = load_safetensors(path)
93
- else:
94
- raise NotImplementedError
95
-
96
- missing, unexpected = self.load_state_dict(sd, strict=False)
97
- print(
98
- f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys"
99
- )
100
- if len(missing) > 0:
101
- print(f"Missing Keys: {missing}")
102
- if len(unexpected) > 0:
103
- print(f"Unexpected Keys: {unexpected}")
104
-
105
- def _init_first_stage(self, config):
106
- model = instantiate_from_config(config).eval()
107
- model.train = disabled_train
108
- for param in model.parameters():
109
- param.requires_grad = False
110
- self.first_stage_model = model
111
-
112
- def get_input(self, batch):
113
- # assuming unified data format, dataloader returns a dict.
114
- # image tensors should be scaled to -1 ... 1 and in bchw format
115
- return batch[self.input_key]
116
-
117
- @torch.no_grad()
118
- def decode_first_stage(self, z):
119
- z = 1.0 / self.scale_factor * z
120
- with torch.autocast("cuda", enabled=not self.disable_first_stage_autocast):
121
- out = self.first_stage_model.decode(z)
122
- return out
123
-
124
- @torch.no_grad()
125
- def encode_first_stage(self, x):
126
- with torch.autocast("cuda", enabled=not self.disable_first_stage_autocast):
127
- z = self.first_stage_model.encode(x)
128
- z = self.scale_factor * z
129
- return z
130
-
131
- def forward(self, x, batch):
132
- loss = self.loss_fn(self.model, self.denoiser, self.conditioner, x, batch)
133
- loss_mean = loss.mean()
134
- loss_dict = {"loss": loss_mean}
135
- return loss_mean, loss_dict
136
-
137
- def shared_step(self, batch: Dict) -> Any:
138
- x = self.get_input(batch)
139
- x = self.encode_first_stage(x)
140
- batch["global_step"] = self.global_step
141
- loss, loss_dict = self(x, batch)
142
- return loss, loss_dict
143
-
144
- def training_step(self, batch, batch_idx):
145
- loss, loss_dict = self.shared_step(batch)
146
-
147
- self.log_dict(
148
- loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=False
149
- )
150
-
151
- self.log(
152
- "global_step",
153
- self.global_step,
154
- prog_bar=True,
155
- logger=True,
156
- on_step=True,
157
- on_epoch=False,
158
- )
159
-
160
- # if self.scheduler_config is not None:
161
- lr = self.optimizers().param_groups[0]["lr"]
162
- self.log(
163
- "lr_abs", lr, prog_bar=True, logger=True, on_step=True, on_epoch=False
164
- )
165
-
166
- return loss
167
-
168
- def on_train_start(self, *args, **kwargs):
169
- if self.sampler is None or self.loss_fn is None:
170
- raise ValueError("Sampler and loss function need to be set for training.")
171
-
172
- def on_train_batch_end(self, *args, **kwargs):
173
- if self.use_ema:
174
- self.model_ema(self.model)
175
-
176
- @contextmanager
177
- def ema_scope(self, context=None):
178
- if self.use_ema:
179
- self.model_ema.store(self.model.parameters())
180
- self.model_ema.copy_to(self.model)
181
- if context is not None:
182
- print(f"{context}: Switched to EMA weights")
183
- try:
184
- yield None
185
- finally:
186
- if self.use_ema:
187
- self.model_ema.restore(self.model.parameters())
188
- if context is not None:
189
- print(f"{context}: Restored training weights")
190
-
191
- def instantiate_optimizer_from_config(self, params, lr, cfg):
192
- return get_obj_from_str(cfg["target"])(
193
- params, lr=lr, **cfg.get("params", dict())
194
- )
195
-
196
- def configure_optimizers(self):
197
- lr = self.learning_rate
198
- params = list(self.model.parameters())
199
- for embedder in self.conditioner.embedders:
200
- if embedder.is_trainable:
201
- params = params + list(embedder.parameters())
202
- opt = self.instantiate_optimizer_from_config(params, lr, self.optimizer_config)
203
- if self.scheduler_config is not None:
204
- scheduler = instantiate_from_config(self.scheduler_config)
205
- print("Setting up LambdaLR scheduler...")
206
- scheduler = [
207
- {
208
- "scheduler": LambdaLR(opt, lr_lambda=scheduler.schedule),
209
- "interval": "step",
210
- "frequency": 1,
211
- }
212
- ]
213
- return [opt], scheduler
214
- return opt
215
-
216
- @torch.no_grad()
217
- def sample(
218
- self,
219
- cond: Dict,
220
- uc: Union[Dict, None] = None,
221
- batch_size: int = 16,
222
- shape: Union[None, Tuple, List] = None,
223
- **kwargs,
224
- ):
225
- randn = torch.randn(batch_size, *shape).to(self.device)
226
-
227
- denoiser = lambda input, sigma, c: self.denoiser(
228
- self.model, input, sigma, c, **kwargs
229
- )
230
- samples = self.sampler(denoiser, randn, cond, uc=uc)
231
- return samples
232
-
233
- @torch.no_grad()
234
- def log_conditionings(self, batch: Dict, n: int) -> Dict:
235
- """
236
- Defines heuristics to log different conditionings.
237
- These can be lists of strings (text-to-image), tensors, ints, ...
238
- """
239
- image_h, image_w = batch[self.input_key].shape[2:]
240
- log = dict()
241
-
242
- for embedder in self.conditioner.embedders:
243
- if (
244
- (self.log_keys is None) or (embedder.input_key in self.log_keys)
245
- ) and not self.no_cond_log:
246
- x = batch[embedder.input_key][:n]
247
- if isinstance(x, torch.Tensor):
248
- if x.dim() == 1:
249
- # class-conditional, convert integer to string
250
- x = [str(x[i].item()) for i in range(x.shape[0])]
251
- xc = log_txt_as_img((image_h, image_w), x, size=image_h // 4)
252
- elif x.dim() == 2:
253
- # size and crop cond and the like
254
- x = [
255
- "x".join([str(xx) for xx in x[i].tolist()])
256
- for i in range(x.shape[0])
257
- ]
258
- xc = log_txt_as_img((image_h, image_w), x, size=image_h // 20)
259
- else:
260
- raise NotImplementedError()
261
- elif isinstance(x, (List, ListConfig)):
262
- if isinstance(x[0], str):
263
- # strings
264
- xc = log_txt_as_img((image_h, image_w), x, size=image_h // 20)
265
- else:
266
- raise NotImplementedError()
267
- else:
268
- raise NotImplementedError()
269
- log[embedder.input_key] = xc
270
- return log
271
-
272
- @torch.no_grad()
273
- def log_images(
274
- self,
275
- batch: Dict,
276
- N: int = 8,
277
- sample: bool = True,
278
- ucg_keys: List[str] = None,
279
- **kwargs,
280
- ) -> Dict:
281
- conditioner_input_keys = [e.input_key for e in self.conditioner.embedders]
282
- if ucg_keys:
283
- assert all(map(lambda x: x in conditioner_input_keys, ucg_keys)), (
284
- "Each defined ucg key for sampling must be in the provided conditioner input keys,"
285
- f"but we have {ucg_keys} vs. {conditioner_input_keys}"
286
- )
287
- else:
288
- ucg_keys = conditioner_input_keys
289
- log = dict()
290
-
291
- x = self.get_input(batch)
292
-
293
- c, uc = self.conditioner.get_unconditional_conditioning(
294
- batch,
295
- force_uc_zero_embeddings=ucg_keys
296
- if len(self.conditioner.embedders) > 0
297
- else [],
298
- )
299
-
300
- sampling_kwargs = {}
301
-
302
- N = min(x.shape[0], N)
303
- x = x.to(self.device)[:N]
304
- log["inputs"] = x
305
- z = self.encode_first_stage(x)
306
- log["reconstructions"] = self.decode_first_stage(z)
307
- log.update(self.log_conditionings(batch, N))
308
-
309
- for k in c:
310
- if isinstance(c[k], torch.Tensor):
311
- c[k], uc[k] = map(lambda y: y[k][:N].to(self.device), (c, uc))
312
-
313
- if sample:
314
- with self.ema_scope("Plotting"):
315
- samples = self.sample(
316
- c, shape=z.shape[1:], uc=uc, batch_size=N, **sampling_kwargs
317
- )
318
- samples = self.decode_first_stage(samples)
319
- log["samples"] = samples
320
- return log
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/__init__.py DELETED
@@ -1,8 +0,0 @@
1
- from .encoders.modules import GeneralConditioner
2
- from .encoders.modules import GeneralConditionerWithControl
3
- from .encoders.modules import PreparedConditioner
4
-
5
- UNCONDITIONAL_CONFIG = {
6
- "target": "sgm.modules.GeneralConditioner",
7
- "params": {"emb_models": []},
8
- }
 
 
 
 
 
 
 
 
 
sgm/modules/attention.py DELETED
@@ -1,635 +0,0 @@
1
- import math
2
- from inspect import isfunction
3
- from typing import Any, Optional
4
-
5
- import torch
6
- import torch.nn.functional as F
7
- # from einops._torch_specific import allow_ops_in_compiled_graph
8
- # allow_ops_in_compiled_graph()
9
- from einops import rearrange, repeat
10
- from packaging import version
11
- from torch import nn
12
-
13
- if version.parse(torch.__version__) >= version.parse("2.0.0"):
14
- SDP_IS_AVAILABLE = True
15
- from torch.backends.cuda import SDPBackend, sdp_kernel
16
-
17
- BACKEND_MAP = {
18
- SDPBackend.MATH: {
19
- "enable_math": True,
20
- "enable_flash": False,
21
- "enable_mem_efficient": False,
22
- },
23
- SDPBackend.FLASH_ATTENTION: {
24
- "enable_math": False,
25
- "enable_flash": True,
26
- "enable_mem_efficient": False,
27
- },
28
- SDPBackend.EFFICIENT_ATTENTION: {
29
- "enable_math": False,
30
- "enable_flash": False,
31
- "enable_mem_efficient": True,
32
- },
33
- None: {"enable_math": True, "enable_flash": True, "enable_mem_efficient": True},
34
- }
35
- else:
36
- from contextlib import nullcontext
37
-
38
- SDP_IS_AVAILABLE = False
39
- sdp_kernel = nullcontext
40
- BACKEND_MAP = {}
41
- print(
42
- f"No SDP backend available, likely because you are running in pytorch versions < 2.0. In fact, "
43
- f"you are using PyTorch {torch.__version__}. You might want to consider upgrading."
44
- )
45
-
46
- try:
47
- import xformers
48
- import xformers.ops
49
-
50
- XFORMERS_IS_AVAILABLE = True
51
- except:
52
- XFORMERS_IS_AVAILABLE = False
53
- print("no module 'xformers'. Processing without...")
54
-
55
- from .diffusionmodules.util import checkpoint
56
-
57
-
58
- def exists(val):
59
- return val is not None
60
-
61
-
62
- def uniq(arr):
63
- return {el: True for el in arr}.keys()
64
-
65
-
66
- def default(val, d):
67
- if exists(val):
68
- return val
69
- return d() if isfunction(d) else d
70
-
71
-
72
- def max_neg_value(t):
73
- return -torch.finfo(t.dtype).max
74
-
75
-
76
- def init_(tensor):
77
- dim = tensor.shape[-1]
78
- std = 1 / math.sqrt(dim)
79
- tensor.uniform_(-std, std)
80
- return tensor
81
-
82
-
83
- # feedforward
84
- class GEGLU(nn.Module):
85
- def __init__(self, dim_in, dim_out):
86
- super().__init__()
87
- self.proj = nn.Linear(dim_in, dim_out * 2)
88
-
89
- def forward(self, x):
90
- x, gate = self.proj(x).chunk(2, dim=-1)
91
- return x * F.gelu(gate)
92
-
93
-
94
- class FeedForward(nn.Module):
95
- def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0):
96
- super().__init__()
97
- inner_dim = int(dim * mult)
98
- dim_out = default(dim_out, dim)
99
- project_in = (
100
- nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU())
101
- if not glu
102
- else GEGLU(dim, inner_dim)
103
- )
104
-
105
- self.net = nn.Sequential(
106
- project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out)
107
- )
108
-
109
- def forward(self, x):
110
- return self.net(x)
111
-
112
-
113
- def zero_module(module):
114
- """
115
- Zero out the parameters of a module and return it.
116
- """
117
- for p in module.parameters():
118
- p.detach().zero_()
119
- return module
120
-
121
-
122
- def Normalize(in_channels):
123
- return torch.nn.GroupNorm(
124
- num_groups=32, num_channels=in_channels, eps=1e-6, affine=True
125
- )
126
-
127
-
128
- class LinearAttention(nn.Module):
129
- def __init__(self, dim, heads=4, dim_head=32):
130
- super().__init__()
131
- self.heads = heads
132
- hidden_dim = dim_head * heads
133
- self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
134
- self.to_out = nn.Conv2d(hidden_dim, dim, 1)
135
-
136
- def forward(self, x):
137
- b, c, h, w = x.shape
138
- qkv = self.to_qkv(x)
139
- q, k, v = rearrange(
140
- qkv, "b (qkv heads c) h w -> qkv b heads c (h w)", heads=self.heads, qkv=3
141
- )
142
- k = k.softmax(dim=-1)
143
- context = torch.einsum("bhdn,bhen->bhde", k, v)
144
- out = torch.einsum("bhde,bhdn->bhen", context, q)
145
- out = rearrange(
146
- out, "b heads c (h w) -> b (heads c) h w", heads=self.heads, h=h, w=w
147
- )
148
- return self.to_out(out)
149
-
150
-
151
- class SpatialSelfAttention(nn.Module):
152
- def __init__(self, in_channels):
153
- super().__init__()
154
- self.in_channels = in_channels
155
-
156
- self.norm = Normalize(in_channels)
157
- self.q = torch.nn.Conv2d(
158
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
159
- )
160
- self.k = torch.nn.Conv2d(
161
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
162
- )
163
- self.v = torch.nn.Conv2d(
164
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
165
- )
166
- self.proj_out = torch.nn.Conv2d(
167
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
168
- )
169
-
170
- def forward(self, x):
171
- h_ = x
172
- h_ = self.norm(h_)
173
- q = self.q(h_)
174
- k = self.k(h_)
175
- v = self.v(h_)
176
-
177
- # compute attention
178
- b, c, h, w = q.shape
179
- q = rearrange(q, "b c h w -> b (h w) c")
180
- k = rearrange(k, "b c h w -> b c (h w)")
181
- w_ = torch.einsum("bij,bjk->bik", q, k)
182
-
183
- w_ = w_ * (int(c) ** (-0.5))
184
- w_ = torch.nn.functional.softmax(w_, dim=2)
185
-
186
- # attend to values
187
- v = rearrange(v, "b c h w -> b c (h w)")
188
- w_ = rearrange(w_, "b i j -> b j i")
189
- h_ = torch.einsum("bij,bjk->bik", v, w_)
190
- h_ = rearrange(h_, "b c (h w) -> b c h w", h=h)
191
- h_ = self.proj_out(h_)
192
-
193
- return x + h_
194
-
195
-
196
- class CrossAttention(nn.Module):
197
- def __init__(
198
- self,
199
- query_dim,
200
- context_dim=None,
201
- heads=8,
202
- dim_head=64,
203
- dropout=0.0,
204
- backend=None,
205
- ):
206
- super().__init__()
207
- inner_dim = dim_head * heads
208
- context_dim = default(context_dim, query_dim)
209
-
210
- self.scale = dim_head**-0.5
211
- self.heads = heads
212
-
213
- self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
214
- self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
215
- self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
216
-
217
- self.to_out = nn.Sequential(
218
- nn.Linear(inner_dim, query_dim), nn.Dropout(dropout)
219
- )
220
- self.backend = backend
221
-
222
- def forward(
223
- self,
224
- x,
225
- context=None,
226
- mask=None,
227
- additional_tokens=None,
228
- n_times_crossframe_attn_in_self=0,
229
- ):
230
- h = self.heads
231
-
232
- if additional_tokens is not None:
233
- # get the number of masked tokens at the beginning of the output sequence
234
- n_tokens_to_mask = additional_tokens.shape[1]
235
- # add additional token
236
- x = torch.cat([additional_tokens, x], dim=1)
237
-
238
- q = self.to_q(x)
239
- context = default(context, x)
240
- k = self.to_k(context)
241
- v = self.to_v(context)
242
-
243
- if n_times_crossframe_attn_in_self:
244
- # reprogramming cross-frame attention as in https://arxiv.org/abs/2303.13439
245
- assert x.shape[0] % n_times_crossframe_attn_in_self == 0
246
- n_cp = x.shape[0] // n_times_crossframe_attn_in_self
247
- k = repeat(
248
- k[::n_times_crossframe_attn_in_self], "b ... -> (b n) ...", n=n_cp
249
- )
250
- v = repeat(
251
- v[::n_times_crossframe_attn_in_self], "b ... -> (b n) ...", n=n_cp
252
- )
253
-
254
- q, k, v = map(lambda t: rearrange(t, "b n (h d) -> b h n d", h=h), (q, k, v))
255
-
256
- ## old
257
- """
258
- sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
259
- del q, k
260
-
261
- if exists(mask):
262
- mask = rearrange(mask, 'b ... -> b (...)')
263
- max_neg_value = -torch.finfo(sim.dtype).max
264
- mask = repeat(mask, 'b j -> (b h) () j', h=h)
265
- sim.masked_fill_(~mask, max_neg_value)
266
-
267
- # attention, what we cannot get enough of
268
- sim = sim.softmax(dim=-1)
269
-
270
- out = einsum('b i j, b j d -> b i d', sim, v)
271
- """
272
- ## new
273
- with sdp_kernel(**BACKEND_MAP[self.backend]):
274
- # print("dispatching into backend", self.backend, "q/k/v shape: ", q.shape, k.shape, v.shape)
275
- out = F.scaled_dot_product_attention(
276
- q, k, v, attn_mask=mask
277
- ) # scale is dim_head ** -0.5 per default
278
-
279
- del q, k, v
280
- out = rearrange(out, "b h n d -> b n (h d)", h=h)
281
-
282
- if additional_tokens is not None:
283
- # remove additional token
284
- out = out[:, n_tokens_to_mask:]
285
- return self.to_out(out)
286
-
287
-
288
- class MemoryEfficientCrossAttention(nn.Module):
289
- # https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
290
- def __init__(
291
- self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0, **kwargs
292
- ):
293
- super().__init__()
294
- print(
295
- f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, context_dim is {context_dim} and using "
296
- f"{heads} heads with a dimension of {dim_head}."
297
- )
298
- inner_dim = dim_head * heads
299
- context_dim = default(context_dim, query_dim)
300
-
301
- self.heads = heads
302
- self.dim_head = dim_head
303
-
304
- self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
305
- self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
306
- self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
307
-
308
- self.to_out = nn.Sequential(
309
- nn.Linear(inner_dim, query_dim), nn.Dropout(dropout)
310
- )
311
- self.attention_op: Optional[Any] = None
312
-
313
- def forward(
314
- self,
315
- x,
316
- context=None,
317
- mask=None,
318
- additional_tokens=None,
319
- n_times_crossframe_attn_in_self=0,
320
- ):
321
- if additional_tokens is not None:
322
- # get the number of masked tokens at the beginning of the output sequence
323
- n_tokens_to_mask = additional_tokens.shape[1]
324
- # add additional token
325
- x = torch.cat([additional_tokens, x], dim=1)
326
- q = self.to_q(x)
327
- context = default(context, x)
328
- k = self.to_k(context)
329
- v = self.to_v(context)
330
-
331
- if n_times_crossframe_attn_in_self:
332
- # reprogramming cross-frame attention as in https://arxiv.org/abs/2303.13439
333
- assert x.shape[0] % n_times_crossframe_attn_in_self == 0
334
- # n_cp = x.shape[0]//n_times_crossframe_attn_in_self
335
- k = repeat(
336
- k[::n_times_crossframe_attn_in_self],
337
- "b ... -> (b n) ...",
338
- n=n_times_crossframe_attn_in_self,
339
- )
340
- v = repeat(
341
- v[::n_times_crossframe_attn_in_self],
342
- "b ... -> (b n) ...",
343
- n=n_times_crossframe_attn_in_self,
344
- )
345
-
346
- b, _, _ = q.shape
347
- q, k, v = map(
348
- lambda t: t.unsqueeze(3)
349
- .reshape(b, t.shape[1], self.heads, self.dim_head)
350
- .permute(0, 2, 1, 3)
351
- .reshape(b * self.heads, t.shape[1], self.dim_head)
352
- .contiguous(),
353
- (q, k, v),
354
- )
355
-
356
- # actually compute the attention, what we cannot get enough of
357
- out = xformers.ops.memory_efficient_attention(
358
- q, k, v, attn_bias=None, op=self.attention_op
359
- )
360
-
361
- # TODO: Use this directly in the attention operation, as a bias
362
- if exists(mask):
363
- raise NotImplementedError
364
- out = (
365
- out.unsqueeze(0)
366
- .reshape(b, self.heads, out.shape[1], self.dim_head)
367
- .permute(0, 2, 1, 3)
368
- .reshape(b, out.shape[1], self.heads * self.dim_head)
369
- )
370
- if additional_tokens is not None:
371
- # remove additional token
372
- out = out[:, n_tokens_to_mask:]
373
- return self.to_out(out)
374
-
375
-
376
- class BasicTransformerBlock(nn.Module):
377
- ATTENTION_MODES = {
378
- "softmax": CrossAttention, # vanilla attention
379
- "softmax-xformers": MemoryEfficientCrossAttention, # ampere
380
- }
381
-
382
- def __init__(
383
- self,
384
- dim,
385
- n_heads,
386
- d_head,
387
- dropout=0.0,
388
- context_dim=None,
389
- gated_ff=True,
390
- checkpoint=True,
391
- disable_self_attn=False,
392
- attn_mode="softmax",
393
- sdp_backend=None,
394
- ):
395
- super().__init__()
396
- assert attn_mode in self.ATTENTION_MODES
397
- if attn_mode != "softmax" and not XFORMERS_IS_AVAILABLE:
398
- print(
399
- f"Attention mode '{attn_mode}' is not available. Falling back to native attention. "
400
- f"This is not a problem in Pytorch >= 2.0. FYI, you are running with PyTorch version {torch.__version__}"
401
- )
402
- attn_mode = "softmax"
403
- elif attn_mode == "softmax" and not SDP_IS_AVAILABLE:
404
- print(
405
- "We do not support vanilla attention anymore, as it is too expensive. Sorry."
406
- )
407
- if not XFORMERS_IS_AVAILABLE:
408
- assert (
409
- False
410
- ), "Please install xformers via e.g. 'pip install xformers==0.0.16'"
411
- else:
412
- print("Falling back to xformers efficient attention.")
413
- attn_mode = "softmax-xformers"
414
- attn_cls = self.ATTENTION_MODES[attn_mode]
415
- if version.parse(torch.__version__) >= version.parse("2.0.0"):
416
- assert sdp_backend is None or isinstance(sdp_backend, SDPBackend)
417
- else:
418
- assert sdp_backend is None
419
- self.disable_self_attn = disable_self_attn
420
- self.attn1 = attn_cls(
421
- query_dim=dim,
422
- heads=n_heads,
423
- dim_head=d_head,
424
- dropout=dropout,
425
- context_dim=context_dim if self.disable_self_attn else None,
426
- backend=sdp_backend,
427
- ) # is a self-attention if not self.disable_self_attn
428
- self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
429
- self.attn2 = attn_cls(
430
- query_dim=dim,
431
- context_dim=context_dim,
432
- heads=n_heads,
433
- dim_head=d_head,
434
- dropout=dropout,
435
- backend=sdp_backend,
436
- ) # is self-attn if context is none
437
- self.norm1 = nn.LayerNorm(dim)
438
- self.norm2 = nn.LayerNorm(dim)
439
- self.norm3 = nn.LayerNorm(dim)
440
- self.checkpoint = checkpoint
441
- if self.checkpoint:
442
- print(f"{self.__class__.__name__} is using checkpointing")
443
-
444
- def forward(
445
- self, x, context=None, additional_tokens=None, n_times_crossframe_attn_in_self=0
446
- ):
447
- kwargs = {"x": x}
448
-
449
- if context is not None:
450
- kwargs.update({"context": context})
451
-
452
- if additional_tokens is not None:
453
- kwargs.update({"additional_tokens": additional_tokens})
454
-
455
- if n_times_crossframe_attn_in_self:
456
- kwargs.update(
457
- {"n_times_crossframe_attn_in_self": n_times_crossframe_attn_in_self}
458
- )
459
-
460
- # return mixed_checkpoint(self._forward, kwargs, self.parameters(), self.checkpoint)
461
- return checkpoint(
462
- self._forward, (x, context), self.parameters(), self.checkpoint
463
- )
464
-
465
- def _forward(
466
- self, x, context=None, additional_tokens=None, n_times_crossframe_attn_in_self=0
467
- ):
468
- x = (
469
- self.attn1(
470
- self.norm1(x),
471
- context=context if self.disable_self_attn else None,
472
- additional_tokens=additional_tokens,
473
- n_times_crossframe_attn_in_self=n_times_crossframe_attn_in_self
474
- if not self.disable_self_attn
475
- else 0,
476
- )
477
- + x
478
- )
479
- x = (
480
- self.attn2(
481
- self.norm2(x), context=context, additional_tokens=additional_tokens
482
- )
483
- + x
484
- )
485
- x = self.ff(self.norm3(x)) + x
486
- return x
487
-
488
-
489
- class BasicTransformerSingleLayerBlock(nn.Module):
490
- ATTENTION_MODES = {
491
- "softmax": CrossAttention, # vanilla attention
492
- "softmax-xformers": MemoryEfficientCrossAttention # on the A100s not quite as fast as the above version
493
- # (todo might depend on head_dim, check, falls back to semi-optimized kernels for dim!=[16,32,64,128])
494
- }
495
-
496
- def __init__(
497
- self,
498
- dim,
499
- n_heads,
500
- d_head,
501
- dropout=0.0,
502
- context_dim=None,
503
- gated_ff=True,
504
- checkpoint=True,
505
- attn_mode="softmax",
506
- ):
507
- super().__init__()
508
- assert attn_mode in self.ATTENTION_MODES
509
- attn_cls = self.ATTENTION_MODES[attn_mode]
510
- self.attn1 = attn_cls(
511
- query_dim=dim,
512
- heads=n_heads,
513
- dim_head=d_head,
514
- dropout=dropout,
515
- context_dim=context_dim,
516
- )
517
- self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
518
- self.norm1 = nn.LayerNorm(dim)
519
- self.norm2 = nn.LayerNorm(dim)
520
- self.checkpoint = checkpoint
521
-
522
- def forward(self, x, context=None):
523
- return checkpoint(
524
- self._forward, (x, context), self.parameters(), self.checkpoint
525
- )
526
-
527
- def _forward(self, x, context=None):
528
- x = self.attn1(self.norm1(x), context=context) + x
529
- x = self.ff(self.norm2(x)) + x
530
- return x
531
-
532
-
533
- class SpatialTransformer(nn.Module):
534
- """
535
- Transformer block for image-like data.
536
- First, project the input (aka embedding)
537
- and reshape to b, t, d.
538
- Then apply standard transformer action.
539
- Finally, reshape to image
540
- NEW: use_linear for more efficiency instead of the 1x1 convs
541
- """
542
-
543
- def __init__(
544
- self,
545
- in_channels,
546
- n_heads,
547
- d_head,
548
- depth=1,
549
- dropout=0.0,
550
- context_dim=None,
551
- disable_self_attn=False,
552
- use_linear=False,
553
- attn_type="softmax",
554
- use_checkpoint=True,
555
- # sdp_backend=SDPBackend.FLASH_ATTENTION
556
- sdp_backend=None,
557
- ):
558
- super().__init__()
559
- print(
560
- f"constructing {self.__class__.__name__} of depth {depth} w/ {in_channels} channels and {n_heads} heads"
561
- )
562
- from omegaconf import ListConfig
563
-
564
- if exists(context_dim) and not isinstance(context_dim, (list, ListConfig)):
565
- context_dim = [context_dim]
566
- if exists(context_dim) and isinstance(context_dim, list):
567
- if depth != len(context_dim):
568
- print(
569
- f"WARNING: {self.__class__.__name__}: Found context dims {context_dim} of depth {len(context_dim)}, "
570
- f"which does not match the specified 'depth' of {depth}. Setting context_dim to {depth * [context_dim[0]]} now."
571
- )
572
- # depth does not match context dims.
573
- assert all(
574
- map(lambda x: x == context_dim[0], context_dim)
575
- ), "need homogenous context_dim to match depth automatically"
576
- context_dim = depth * [context_dim[0]]
577
- elif context_dim is None:
578
- context_dim = [None] * depth
579
- self.in_channels = in_channels
580
- inner_dim = n_heads * d_head
581
- self.norm = Normalize(in_channels)
582
- if not use_linear:
583
- self.proj_in = nn.Conv2d(
584
- in_channels, inner_dim, kernel_size=1, stride=1, padding=0
585
- )
586
- else:
587
- self.proj_in = nn.Linear(in_channels, inner_dim)
588
-
589
- self.transformer_blocks = nn.ModuleList(
590
- [
591
- BasicTransformerBlock(
592
- inner_dim,
593
- n_heads,
594
- d_head,
595
- dropout=dropout,
596
- context_dim=context_dim[d],
597
- disable_self_attn=disable_self_attn,
598
- attn_mode=attn_type,
599
- checkpoint=use_checkpoint,
600
- sdp_backend=sdp_backend,
601
- )
602
- for d in range(depth)
603
- ]
604
- )
605
- if not use_linear:
606
- self.proj_out = zero_module(
607
- nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
608
- )
609
- else:
610
- # self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))
611
- self.proj_out = zero_module(nn.Linear(inner_dim, in_channels))
612
- self.use_linear = use_linear
613
-
614
- def forward(self, x, context=None):
615
- # note: if no context is given, cross-attention defaults to self-attention
616
- if not isinstance(context, list):
617
- context = [context]
618
- b, c, h, w = x.shape
619
- x_in = x
620
- x = self.norm(x)
621
- if not self.use_linear:
622
- x = self.proj_in(x)
623
- x = rearrange(x, "b c h w -> b (h w) c").contiguous()
624
- if self.use_linear:
625
- x = self.proj_in(x)
626
- for i, block in enumerate(self.transformer_blocks):
627
- if i > 0 and len(context) == 1:
628
- i = 0 # use same context for each block
629
- x = block(x, context=context[i])
630
- if self.use_linear:
631
- x = self.proj_out(x)
632
- x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w).contiguous()
633
- if not self.use_linear:
634
- x = self.proj_out(x)
635
- return x + x_in
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/autoencoding/__init__.py DELETED
File without changes
sgm/modules/autoencoding/losses/__init__.py DELETED
@@ -1,246 +0,0 @@
1
- from typing import Any, Union
2
-
3
- import torch
4
- import torch.nn as nn
5
- from einops import rearrange
6
-
7
- from ....util import default, instantiate_from_config
8
- from ..lpips.loss.lpips import LPIPS
9
- from ..lpips.model.model import NLayerDiscriminator, weights_init
10
- from ..lpips.vqperceptual import hinge_d_loss, vanilla_d_loss
11
-
12
-
13
- def adopt_weight(weight, global_step, threshold=0, value=0.0):
14
- if global_step < threshold:
15
- weight = value
16
- return weight
17
-
18
-
19
- class LatentLPIPS(nn.Module):
20
- def __init__(
21
- self,
22
- decoder_config,
23
- perceptual_weight=1.0,
24
- latent_weight=1.0,
25
- scale_input_to_tgt_size=False,
26
- scale_tgt_to_input_size=False,
27
- perceptual_weight_on_inputs=0.0,
28
- ):
29
- super().__init__()
30
- self.scale_input_to_tgt_size = scale_input_to_tgt_size
31
- self.scale_tgt_to_input_size = scale_tgt_to_input_size
32
- self.init_decoder(decoder_config)
33
- self.perceptual_loss = LPIPS().eval()
34
- self.perceptual_weight = perceptual_weight
35
- self.latent_weight = latent_weight
36
- self.perceptual_weight_on_inputs = perceptual_weight_on_inputs
37
-
38
- def init_decoder(self, config):
39
- self.decoder = instantiate_from_config(config)
40
- if hasattr(self.decoder, "encoder"):
41
- del self.decoder.encoder
42
-
43
- def forward(self, latent_inputs, latent_predictions, image_inputs, split="train"):
44
- log = dict()
45
- loss = (latent_inputs - latent_predictions) ** 2
46
- log[f"{split}/latent_l2_loss"] = loss.mean().detach()
47
- image_reconstructions = None
48
- if self.perceptual_weight > 0.0:
49
- image_reconstructions = self.decoder.decode(latent_predictions)
50
- image_targets = self.decoder.decode(latent_inputs)
51
- perceptual_loss = self.perceptual_loss(
52
- image_targets.contiguous(), image_reconstructions.contiguous()
53
- )
54
- loss = (
55
- self.latent_weight * loss.mean()
56
- + self.perceptual_weight * perceptual_loss.mean()
57
- )
58
- log[f"{split}/perceptual_loss"] = perceptual_loss.mean().detach()
59
-
60
- if self.perceptual_weight_on_inputs > 0.0:
61
- image_reconstructions = default(
62
- image_reconstructions, self.decoder.decode(latent_predictions)
63
- )
64
- if self.scale_input_to_tgt_size:
65
- image_inputs = torch.nn.functional.interpolate(
66
- image_inputs,
67
- image_reconstructions.shape[2:],
68
- mode="bicubic",
69
- antialias=True,
70
- )
71
- elif self.scale_tgt_to_input_size:
72
- image_reconstructions = torch.nn.functional.interpolate(
73
- image_reconstructions,
74
- image_inputs.shape[2:],
75
- mode="bicubic",
76
- antialias=True,
77
- )
78
-
79
- perceptual_loss2 = self.perceptual_loss(
80
- image_inputs.contiguous(), image_reconstructions.contiguous()
81
- )
82
- loss = loss + self.perceptual_weight_on_inputs * perceptual_loss2.mean()
83
- log[f"{split}/perceptual_loss_on_inputs"] = perceptual_loss2.mean().detach()
84
- return loss, log
85
-
86
-
87
- class GeneralLPIPSWithDiscriminator(nn.Module):
88
- def __init__(
89
- self,
90
- disc_start: int,
91
- logvar_init: float = 0.0,
92
- pixelloss_weight=1.0,
93
- disc_num_layers: int = 3,
94
- disc_in_channels: int = 3,
95
- disc_factor: float = 1.0,
96
- disc_weight: float = 1.0,
97
- perceptual_weight: float = 1.0,
98
- disc_loss: str = "hinge",
99
- scale_input_to_tgt_size: bool = False,
100
- dims: int = 2,
101
- learn_logvar: bool = False,
102
- regularization_weights: Union[None, dict] = None,
103
- ):
104
- super().__init__()
105
- self.dims = dims
106
- if self.dims > 2:
107
- print(
108
- f"running with dims={dims}. This means that for perceptual loss calculation, "
109
- f"the LPIPS loss will be applied to each frame independently. "
110
- )
111
- self.scale_input_to_tgt_size = scale_input_to_tgt_size
112
- assert disc_loss in ["hinge", "vanilla"]
113
- self.pixel_weight = pixelloss_weight
114
- self.perceptual_loss = LPIPS().eval()
115
- self.perceptual_weight = perceptual_weight
116
- # output log variance
117
- self.logvar = nn.Parameter(torch.ones(size=()) * logvar_init)
118
- self.learn_logvar = learn_logvar
119
-
120
- self.discriminator = NLayerDiscriminator(
121
- input_nc=disc_in_channels, n_layers=disc_num_layers, use_actnorm=False
122
- ).apply(weights_init)
123
- self.discriminator_iter_start = disc_start
124
- self.disc_loss = hinge_d_loss if disc_loss == "hinge" else vanilla_d_loss
125
- self.disc_factor = disc_factor
126
- self.discriminator_weight = disc_weight
127
- self.regularization_weights = default(regularization_weights, {})
128
-
129
- def get_trainable_parameters(self) -> Any:
130
- return self.discriminator.parameters()
131
-
132
- def get_trainable_autoencoder_parameters(self) -> Any:
133
- if self.learn_logvar:
134
- yield self.logvar
135
- yield from ()
136
-
137
- def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None):
138
- if last_layer is not None:
139
- nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0]
140
- g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
141
- else:
142
- nll_grads = torch.autograd.grad(
143
- nll_loss, self.last_layer[0], retain_graph=True
144
- )[0]
145
- g_grads = torch.autograd.grad(
146
- g_loss, self.last_layer[0], retain_graph=True
147
- )[0]
148
-
149
- d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
150
- d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
151
- d_weight = d_weight * self.discriminator_weight
152
- return d_weight
153
-
154
- def forward(
155
- self,
156
- regularization_log,
157
- inputs,
158
- reconstructions,
159
- optimizer_idx,
160
- global_step,
161
- last_layer=None,
162
- split="train",
163
- weights=None,
164
- ):
165
- if self.scale_input_to_tgt_size:
166
- inputs = torch.nn.functional.interpolate(
167
- inputs, reconstructions.shape[2:], mode="bicubic", antialias=True
168
- )
169
-
170
- if self.dims > 2:
171
- inputs, reconstructions = map(
172
- lambda x: rearrange(x, "b c t h w -> (b t) c h w"),
173
- (inputs, reconstructions),
174
- )
175
-
176
- rec_loss = torch.abs(inputs.contiguous() - reconstructions.contiguous())
177
- if self.perceptual_weight > 0:
178
- p_loss = self.perceptual_loss(
179
- inputs.contiguous(), reconstructions.contiguous()
180
- )
181
- rec_loss = rec_loss + self.perceptual_weight * p_loss
182
-
183
- nll_loss = rec_loss / torch.exp(self.logvar) + self.logvar
184
- weighted_nll_loss = nll_loss
185
- if weights is not None:
186
- weighted_nll_loss = weights * nll_loss
187
- weighted_nll_loss = torch.sum(weighted_nll_loss) / weighted_nll_loss.shape[0]
188
- nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]
189
-
190
- # now the GAN part
191
- if optimizer_idx == 0:
192
- # generator update
193
- logits_fake = self.discriminator(reconstructions.contiguous())
194
- g_loss = -torch.mean(logits_fake)
195
-
196
- if self.disc_factor > 0.0:
197
- try:
198
- d_weight = self.calculate_adaptive_weight(
199
- nll_loss, g_loss, last_layer=last_layer
200
- )
201
- except RuntimeError:
202
- assert not self.training
203
- d_weight = torch.tensor(0.0)
204
- else:
205
- d_weight = torch.tensor(0.0)
206
-
207
- disc_factor = adopt_weight(
208
- self.disc_factor, global_step, threshold=self.discriminator_iter_start
209
- )
210
- loss = weighted_nll_loss + d_weight * disc_factor * g_loss
211
- log = dict()
212
- for k in regularization_log:
213
- if k in self.regularization_weights:
214
- loss = loss + self.regularization_weights[k] * regularization_log[k]
215
- log[f"{split}/{k}"] = regularization_log[k].detach().mean()
216
-
217
- log.update(
218
- {
219
- "{}/total_loss".format(split): loss.clone().detach().mean(),
220
- "{}/logvar".format(split): self.logvar.detach(),
221
- "{}/nll_loss".format(split): nll_loss.detach().mean(),
222
- "{}/rec_loss".format(split): rec_loss.detach().mean(),
223
- "{}/d_weight".format(split): d_weight.detach(),
224
- "{}/disc_factor".format(split): torch.tensor(disc_factor),
225
- "{}/g_loss".format(split): g_loss.detach().mean(),
226
- }
227
- )
228
-
229
- return loss, log
230
-
231
- if optimizer_idx == 1:
232
- # second pass for discriminator update
233
- logits_real = self.discriminator(inputs.contiguous().detach())
234
- logits_fake = self.discriminator(reconstructions.contiguous().detach())
235
-
236
- disc_factor = adopt_weight(
237
- self.disc_factor, global_step, threshold=self.discriminator_iter_start
238
- )
239
- d_loss = disc_factor * self.disc_loss(logits_real, logits_fake)
240
-
241
- log = {
242
- "{}/disc_loss".format(split): d_loss.clone().detach().mean(),
243
- "{}/logits_real".format(split): logits_real.detach().mean(),
244
- "{}/logits_fake".format(split): logits_fake.detach().mean(),
245
- }
246
- return d_loss, log
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/autoencoding/lpips/__init__.py DELETED
File without changes
sgm/modules/autoencoding/lpips/loss/LICENSE DELETED
@@ -1,23 +0,0 @@
1
- Copyright (c) 2018, Richard Zhang, Phillip Isola, Alexei A. Efros, Eli Shechtman, Oliver Wang
2
- All rights reserved.
3
-
4
- Redistribution and use in source and binary forms, with or without
5
- modification, are permitted provided that the following conditions are met:
6
-
7
- * Redistributions of source code must retain the above copyright notice, this
8
- list of conditions and the following disclaimer.
9
-
10
- * Redistributions in binary form must reproduce the above copyright notice,
11
- this list of conditions and the following disclaimer in the documentation
12
- and/or other materials provided with the distribution.
13
-
14
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18
- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20
- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21
- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22
- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23
- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/autoencoding/lpips/loss/__init__.py DELETED
File without changes
sgm/modules/autoencoding/lpips/loss/lpips.py DELETED
@@ -1,147 +0,0 @@
1
- """Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models"""
2
-
3
- from collections import namedtuple
4
-
5
- import torch
6
- import torch.nn as nn
7
- from torchvision import models
8
-
9
- from ..util import get_ckpt_path
10
-
11
-
12
- class LPIPS(nn.Module):
13
- # Learned perceptual metric
14
- def __init__(self, use_dropout=True):
15
- super().__init__()
16
- self.scaling_layer = ScalingLayer()
17
- self.chns = [64, 128, 256, 512, 512] # vg16 features
18
- self.net = vgg16(pretrained=True, requires_grad=False)
19
- self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout)
20
- self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout)
21
- self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout)
22
- self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout)
23
- self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout)
24
- self.load_from_pretrained()
25
- for param in self.parameters():
26
- param.requires_grad = False
27
-
28
- def load_from_pretrained(self, name="vgg_lpips"):
29
- ckpt = get_ckpt_path(name, "sgm/modules/autoencoding/lpips/loss")
30
- self.load_state_dict(
31
- torch.load(ckpt, map_location=torch.device("cpu")), strict=False
32
- )
33
- print("loaded pretrained LPIPS loss from {}".format(ckpt))
34
-
35
- @classmethod
36
- def from_pretrained(cls, name="vgg_lpips"):
37
- if name != "vgg_lpips":
38
- raise NotImplementedError
39
- model = cls()
40
- ckpt = get_ckpt_path(name)
41
- model.load_state_dict(
42
- torch.load(ckpt, map_location=torch.device("cpu")), strict=False
43
- )
44
- return model
45
-
46
- def forward(self, input, target):
47
- in0_input, in1_input = (self.scaling_layer(input), self.scaling_layer(target))
48
- outs0, outs1 = self.net(in0_input), self.net(in1_input)
49
- feats0, feats1, diffs = {}, {}, {}
50
- lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4]
51
- for kk in range(len(self.chns)):
52
- feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(
53
- outs1[kk]
54
- )
55
- diffs[kk] = (feats0[kk] - feats1[kk]) ** 2
56
-
57
- res = [
58
- spatial_average(lins[kk].model(diffs[kk]), keepdim=True)
59
- for kk in range(len(self.chns))
60
- ]
61
- val = res[0]
62
- for l in range(1, len(self.chns)):
63
- val += res[l]
64
- return val
65
-
66
-
67
- class ScalingLayer(nn.Module):
68
- def __init__(self):
69
- super(ScalingLayer, self).__init__()
70
- self.register_buffer(
71
- "shift", torch.Tensor([-0.030, -0.088, -0.188])[None, :, None, None]
72
- )
73
- self.register_buffer(
74
- "scale", torch.Tensor([0.458, 0.448, 0.450])[None, :, None, None]
75
- )
76
-
77
- def forward(self, inp):
78
- return (inp - self.shift) / self.scale
79
-
80
-
81
- class NetLinLayer(nn.Module):
82
- """A single linear layer which does a 1x1 conv"""
83
-
84
- def __init__(self, chn_in, chn_out=1, use_dropout=False):
85
- super(NetLinLayer, self).__init__()
86
- layers = (
87
- [
88
- nn.Dropout(),
89
- ]
90
- if (use_dropout)
91
- else []
92
- )
93
- layers += [
94
- nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False),
95
- ]
96
- self.model = nn.Sequential(*layers)
97
-
98
-
99
- class vgg16(torch.nn.Module):
100
- def __init__(self, requires_grad=False, pretrained=True):
101
- super(vgg16, self).__init__()
102
- vgg_pretrained_features = models.vgg16(pretrained=pretrained).features
103
- self.slice1 = torch.nn.Sequential()
104
- self.slice2 = torch.nn.Sequential()
105
- self.slice3 = torch.nn.Sequential()
106
- self.slice4 = torch.nn.Sequential()
107
- self.slice5 = torch.nn.Sequential()
108
- self.N_slices = 5
109
- for x in range(4):
110
- self.slice1.add_module(str(x), vgg_pretrained_features[x])
111
- for x in range(4, 9):
112
- self.slice2.add_module(str(x), vgg_pretrained_features[x])
113
- for x in range(9, 16):
114
- self.slice3.add_module(str(x), vgg_pretrained_features[x])
115
- for x in range(16, 23):
116
- self.slice4.add_module(str(x), vgg_pretrained_features[x])
117
- for x in range(23, 30):
118
- self.slice5.add_module(str(x), vgg_pretrained_features[x])
119
- if not requires_grad:
120
- for param in self.parameters():
121
- param.requires_grad = False
122
-
123
- def forward(self, X):
124
- h = self.slice1(X)
125
- h_relu1_2 = h
126
- h = self.slice2(h)
127
- h_relu2_2 = h
128
- h = self.slice3(h)
129
- h_relu3_3 = h
130
- h = self.slice4(h)
131
- h_relu4_3 = h
132
- h = self.slice5(h)
133
- h_relu5_3 = h
134
- vgg_outputs = namedtuple(
135
- "VggOutputs", ["relu1_2", "relu2_2", "relu3_3", "relu4_3", "relu5_3"]
136
- )
137
- out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3)
138
- return out
139
-
140
-
141
- def normalize_tensor(x, eps=1e-10):
142
- norm_factor = torch.sqrt(torch.sum(x**2, dim=1, keepdim=True))
143
- return x / (norm_factor + eps)
144
-
145
-
146
- def spatial_average(x, keepdim=True):
147
- return x.mean([2, 3], keepdim=keepdim)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/autoencoding/lpips/model/LICENSE DELETED
@@ -1,58 +0,0 @@
1
- Copyright (c) 2017, Jun-Yan Zhu and Taesung Park
2
- All rights reserved.
3
-
4
- Redistribution and use in source and binary forms, with or without
5
- modification, are permitted provided that the following conditions are met:
6
-
7
- * Redistributions of source code must retain the above copyright notice, this
8
- list of conditions and the following disclaimer.
9
-
10
- * Redistributions in binary form must reproduce the above copyright notice,
11
- this list of conditions and the following disclaimer in the documentation
12
- and/or other materials provided with the distribution.
13
-
14
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18
- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20
- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21
- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22
- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23
- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24
-
25
-
26
- --------------------------- LICENSE FOR pix2pix --------------------------------
27
- BSD License
28
-
29
- For pix2pix software
30
- Copyright (c) 2016, Phillip Isola and Jun-Yan Zhu
31
- All rights reserved.
32
-
33
- Redistribution and use in source and binary forms, with or without
34
- modification, are permitted provided that the following conditions are met:
35
-
36
- * Redistributions of source code must retain the above copyright notice, this
37
- list of conditions and the following disclaimer.
38
-
39
- * Redistributions in binary form must reproduce the above copyright notice,
40
- this list of conditions and the following disclaimer in the documentation
41
- and/or other materials provided with the distribution.
42
-
43
- ----------------------------- LICENSE FOR DCGAN --------------------------------
44
- BSD License
45
-
46
- For dcgan.torch software
47
-
48
- Copyright (c) 2015, Facebook, Inc. All rights reserved.
49
-
50
- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
51
-
52
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
53
-
54
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
55
-
56
- Neither the name Facebook nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
57
-
58
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/autoencoding/lpips/model/__init__.py DELETED
File without changes
sgm/modules/autoencoding/lpips/model/model.py DELETED
@@ -1,88 +0,0 @@
1
- import functools
2
-
3
- import torch.nn as nn
4
-
5
- from ..util import ActNorm
6
-
7
-
8
- def weights_init(m):
9
- classname = m.__class__.__name__
10
- if classname.find("Conv") != -1:
11
- nn.init.normal_(m.weight.data, 0.0, 0.02)
12
- elif classname.find("BatchNorm") != -1:
13
- nn.init.normal_(m.weight.data, 1.0, 0.02)
14
- nn.init.constant_(m.bias.data, 0)
15
-
16
-
17
- class NLayerDiscriminator(nn.Module):
18
- """Defines a PatchGAN discriminator as in Pix2Pix
19
- --> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
20
- """
21
-
22
- def __init__(self, input_nc=3, ndf=64, n_layers=3, use_actnorm=False):
23
- """Construct a PatchGAN discriminator
24
- Parameters:
25
- input_nc (int) -- the number of channels in input images
26
- ndf (int) -- the number of filters in the last conv layer
27
- n_layers (int) -- the number of conv layers in the discriminator
28
- norm_layer -- normalization layer
29
- """
30
- super(NLayerDiscriminator, self).__init__()
31
- if not use_actnorm:
32
- norm_layer = nn.BatchNorm2d
33
- else:
34
- norm_layer = ActNorm
35
- if (
36
- type(norm_layer) == functools.partial
37
- ): # no need to use bias as BatchNorm2d has affine parameters
38
- use_bias = norm_layer.func != nn.BatchNorm2d
39
- else:
40
- use_bias = norm_layer != nn.BatchNorm2d
41
-
42
- kw = 4
43
- padw = 1
44
- sequence = [
45
- nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw),
46
- nn.LeakyReLU(0.2, True),
47
- ]
48
- nf_mult = 1
49
- nf_mult_prev = 1
50
- for n in range(1, n_layers): # gradually increase the number of filters
51
- nf_mult_prev = nf_mult
52
- nf_mult = min(2**n, 8)
53
- sequence += [
54
- nn.Conv2d(
55
- ndf * nf_mult_prev,
56
- ndf * nf_mult,
57
- kernel_size=kw,
58
- stride=2,
59
- padding=padw,
60
- bias=use_bias,
61
- ),
62
- norm_layer(ndf * nf_mult),
63
- nn.LeakyReLU(0.2, True),
64
- ]
65
-
66
- nf_mult_prev = nf_mult
67
- nf_mult = min(2**n_layers, 8)
68
- sequence += [
69
- nn.Conv2d(
70
- ndf * nf_mult_prev,
71
- ndf * nf_mult,
72
- kernel_size=kw,
73
- stride=1,
74
- padding=padw,
75
- bias=use_bias,
76
- ),
77
- norm_layer(ndf * nf_mult),
78
- nn.LeakyReLU(0.2, True),
79
- ]
80
-
81
- sequence += [
82
- nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)
83
- ] # output 1 channel prediction map
84
- self.main = nn.Sequential(*sequence)
85
-
86
- def forward(self, input):
87
- """Standard forward."""
88
- return self.main(input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/autoencoding/lpips/util.py DELETED
@@ -1,128 +0,0 @@
1
- import hashlib
2
- import os
3
-
4
- import requests
5
- import torch
6
- import torch.nn as nn
7
- from tqdm import tqdm
8
-
9
- URL_MAP = {"vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"}
10
-
11
- CKPT_MAP = {"vgg_lpips": "vgg.pth"}
12
-
13
- MD5_MAP = {"vgg_lpips": "d507d7349b931f0638a25a48a722f98a"}
14
-
15
-
16
- def download(url, local_path, chunk_size=1024):
17
- os.makedirs(os.path.split(local_path)[0], exist_ok=True)
18
- with requests.get(url, stream=True) as r:
19
- total_size = int(r.headers.get("content-length", 0))
20
- with tqdm(total=total_size, unit="B", unit_scale=True) as pbar:
21
- with open(local_path, "wb") as f:
22
- for data in r.iter_content(chunk_size=chunk_size):
23
- if data:
24
- f.write(data)
25
- pbar.update(chunk_size)
26
-
27
-
28
- def md5_hash(path):
29
- with open(path, "rb") as f:
30
- content = f.read()
31
- return hashlib.md5(content).hexdigest()
32
-
33
-
34
- def get_ckpt_path(name, root, check=False):
35
- assert name in URL_MAP
36
- path = os.path.join(root, CKPT_MAP[name])
37
- if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]):
38
- print("Downloading {} model from {} to {}".format(name, URL_MAP[name], path))
39
- download(URL_MAP[name], path)
40
- md5 = md5_hash(path)
41
- assert md5 == MD5_MAP[name], md5
42
- return path
43
-
44
-
45
- class ActNorm(nn.Module):
46
- def __init__(
47
- self, num_features, logdet=False, affine=True, allow_reverse_init=False
48
- ):
49
- assert affine
50
- super().__init__()
51
- self.logdet = logdet
52
- self.loc = nn.Parameter(torch.zeros(1, num_features, 1, 1))
53
- self.scale = nn.Parameter(torch.ones(1, num_features, 1, 1))
54
- self.allow_reverse_init = allow_reverse_init
55
-
56
- self.register_buffer("initialized", torch.tensor(0, dtype=torch.uint8))
57
-
58
- def initialize(self, input):
59
- with torch.no_grad():
60
- flatten = input.permute(1, 0, 2, 3).contiguous().view(input.shape[1], -1)
61
- mean = (
62
- flatten.mean(1)
63
- .unsqueeze(1)
64
- .unsqueeze(2)
65
- .unsqueeze(3)
66
- .permute(1, 0, 2, 3)
67
- )
68
- std = (
69
- flatten.std(1)
70
- .unsqueeze(1)
71
- .unsqueeze(2)
72
- .unsqueeze(3)
73
- .permute(1, 0, 2, 3)
74
- )
75
-
76
- self.loc.data.copy_(-mean)
77
- self.scale.data.copy_(1 / (std + 1e-6))
78
-
79
- def forward(self, input, reverse=False):
80
- if reverse:
81
- return self.reverse(input)
82
- if len(input.shape) == 2:
83
- input = input[:, :, None, None]
84
- squeeze = True
85
- else:
86
- squeeze = False
87
-
88
- _, _, height, width = input.shape
89
-
90
- if self.training and self.initialized.item() == 0:
91
- self.initialize(input)
92
- self.initialized.fill_(1)
93
-
94
- h = self.scale * (input + self.loc)
95
-
96
- if squeeze:
97
- h = h.squeeze(-1).squeeze(-1)
98
-
99
- if self.logdet:
100
- log_abs = torch.log(torch.abs(self.scale))
101
- logdet = height * width * torch.sum(log_abs)
102
- logdet = logdet * torch.ones(input.shape[0]).to(input)
103
- return h, logdet
104
-
105
- return h
106
-
107
- def reverse(self, output):
108
- if self.training and self.initialized.item() == 0:
109
- if not self.allow_reverse_init:
110
- raise RuntimeError(
111
- "Initializing ActNorm in reverse direction is "
112
- "disabled by default. Use allow_reverse_init=True to enable."
113
- )
114
- else:
115
- self.initialize(output)
116
- self.initialized.fill_(1)
117
-
118
- if len(output.shape) == 2:
119
- output = output[:, :, None, None]
120
- squeeze = True
121
- else:
122
- squeeze = False
123
-
124
- h = output / self.scale - self.loc
125
-
126
- if squeeze:
127
- h = h.squeeze(-1).squeeze(-1)
128
- return h
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/autoencoding/lpips/vqperceptual.py DELETED
@@ -1,17 +0,0 @@
1
- import torch
2
- import torch.nn.functional as F
3
-
4
-
5
- def hinge_d_loss(logits_real, logits_fake):
6
- loss_real = torch.mean(F.relu(1.0 - logits_real))
7
- loss_fake = torch.mean(F.relu(1.0 + logits_fake))
8
- d_loss = 0.5 * (loss_real + loss_fake)
9
- return d_loss
10
-
11
-
12
- def vanilla_d_loss(logits_real, logits_fake):
13
- d_loss = 0.5 * (
14
- torch.mean(torch.nn.functional.softplus(-logits_real))
15
- + torch.mean(torch.nn.functional.softplus(logits_fake))
16
- )
17
- return d_loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/autoencoding/regularizers/__init__.py DELETED
@@ -1,53 +0,0 @@
1
- from abc import abstractmethod
2
- from typing import Any, Tuple
3
-
4
- import torch
5
- import torch.nn as nn
6
- import torch.nn.functional as F
7
-
8
- from ....modules.distributions.distributions import DiagonalGaussianDistribution
9
-
10
-
11
- class AbstractRegularizer(nn.Module):
12
- def __init__(self):
13
- super().__init__()
14
-
15
- def forward(self, z: torch.Tensor) -> Tuple[torch.Tensor, dict]:
16
- raise NotImplementedError()
17
-
18
- @abstractmethod
19
- def get_trainable_parameters(self) -> Any:
20
- raise NotImplementedError()
21
-
22
-
23
- class DiagonalGaussianRegularizer(AbstractRegularizer):
24
- def __init__(self, sample: bool = True):
25
- super().__init__()
26
- self.sample = sample
27
-
28
- def get_trainable_parameters(self) -> Any:
29
- yield from ()
30
-
31
- def forward(self, z: torch.Tensor) -> Tuple[torch.Tensor, dict]:
32
- log = dict()
33
- posterior = DiagonalGaussianDistribution(z)
34
- if self.sample:
35
- z = posterior.sample()
36
- else:
37
- z = posterior.mode()
38
- kl_loss = posterior.kl()
39
- kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]
40
- log["kl_loss"] = kl_loss
41
- return z, log
42
-
43
-
44
- def measure_perplexity(predicted_indices, num_centroids):
45
- # src: https://github.com/karpathy/deep-vector-quantization/blob/main/model.py
46
- # eval cluster perplexity. when perplexity == num_embeddings then all clusters are used exactly equally
47
- encodings = (
48
- F.one_hot(predicted_indices, num_centroids).float().reshape(-1, num_centroids)
49
- )
50
- avg_probs = encodings.mean(0)
51
- perplexity = (-(avg_probs * torch.log(avg_probs + 1e-10)).sum()).exp()
52
- cluster_use = torch.sum(avg_probs > 0)
53
- return perplexity, cluster_use
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/__init__.py DELETED
@@ -1,7 +0,0 @@
1
- from .denoiser import Denoiser
2
- from .discretizer import Discretization
3
- from .loss import StandardDiffusionLoss
4
- from .model import Decoder, Encoder, Model
5
- from .openaimodel import UNetModel
6
- from .sampling import BaseDiffusionSampler
7
- from .wrappers import OpenAIWrapper
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/denoiser.py DELETED
@@ -1,73 +0,0 @@
1
- import torch.nn as nn
2
-
3
- from ...util import append_dims, instantiate_from_config
4
-
5
-
6
- class Denoiser(nn.Module):
7
- def __init__(self, weighting_config, scaling_config):
8
- super().__init__()
9
-
10
- self.weighting = instantiate_from_config(weighting_config)
11
- self.scaling = instantiate_from_config(scaling_config)
12
-
13
- def possibly_quantize_sigma(self, sigma):
14
- return sigma
15
-
16
- def possibly_quantize_c_noise(self, c_noise):
17
- return c_noise
18
-
19
- def w(self, sigma):
20
- return self.weighting(sigma)
21
-
22
- def __call__(self, network, input, sigma, cond):
23
- sigma = self.possibly_quantize_sigma(sigma)
24
- sigma_shape = sigma.shape
25
- sigma = append_dims(sigma, input.ndim)
26
- c_skip, c_out, c_in, c_noise = self.scaling(sigma)
27
- c_noise = self.possibly_quantize_c_noise(c_noise.reshape(sigma_shape))
28
- return network(input * c_in, c_noise, cond) * c_out + input * c_skip
29
-
30
-
31
- class DiscreteDenoiser(Denoiser):
32
- def __init__(
33
- self,
34
- weighting_config,
35
- scaling_config,
36
- num_idx,
37
- discretization_config,
38
- do_append_zero=False,
39
- quantize_c_noise=True,
40
- flip=True,
41
- ):
42
- super().__init__(weighting_config, scaling_config)
43
- sigmas = instantiate_from_config(discretization_config)(
44
- num_idx, do_append_zero=do_append_zero, flip=flip
45
- )
46
- self.register_buffer("sigmas", sigmas)
47
- self.quantize_c_noise = quantize_c_noise
48
-
49
- def sigma_to_idx(self, sigma):
50
- dists = sigma - self.sigmas[:, None]
51
- return dists.abs().argmin(dim=0).view(sigma.shape)
52
-
53
- def idx_to_sigma(self, idx):
54
- return self.sigmas[idx]
55
-
56
- def possibly_quantize_sigma(self, sigma):
57
- return self.idx_to_sigma(self.sigma_to_idx(sigma))
58
-
59
- def possibly_quantize_c_noise(self, c_noise):
60
- if self.quantize_c_noise:
61
- return self.sigma_to_idx(c_noise)
62
- else:
63
- return c_noise
64
-
65
-
66
- class DiscreteDenoiserWithControl(DiscreteDenoiser):
67
- def __call__(self, network, input, sigma, cond, control_scale):
68
- sigma = self.possibly_quantize_sigma(sigma)
69
- sigma_shape = sigma.shape
70
- sigma = append_dims(sigma, input.ndim)
71
- c_skip, c_out, c_in, c_noise = self.scaling(sigma)
72
- c_noise = self.possibly_quantize_c_noise(c_noise.reshape(sigma_shape))
73
- return network(input * c_in, c_noise, cond, control_scale) * c_out + input * c_skip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/denoiser_scaling.py DELETED
@@ -1,31 +0,0 @@
1
- import torch
2
-
3
-
4
- class EDMScaling:
5
- def __init__(self, sigma_data=0.5):
6
- self.sigma_data = sigma_data
7
-
8
- def __call__(self, sigma):
9
- c_skip = self.sigma_data**2 / (sigma**2 + self.sigma_data**2)
10
- c_out = sigma * self.sigma_data / (sigma**2 + self.sigma_data**2) ** 0.5
11
- c_in = 1 / (sigma**2 + self.sigma_data**2) ** 0.5
12
- c_noise = 0.25 * sigma.log()
13
- return c_skip, c_out, c_in, c_noise
14
-
15
-
16
- class EpsScaling:
17
- def __call__(self, sigma):
18
- c_skip = torch.ones_like(sigma, device=sigma.device)
19
- c_out = -sigma
20
- c_in = 1 / (sigma**2 + 1.0) ** 0.5
21
- c_noise = sigma.clone()
22
- return c_skip, c_out, c_in, c_noise
23
-
24
-
25
- class VScaling:
26
- def __call__(self, sigma):
27
- c_skip = 1.0 / (sigma**2 + 1.0)
28
- c_out = -sigma / (sigma**2 + 1.0) ** 0.5
29
- c_in = 1.0 / (sigma**2 + 1.0) ** 0.5
30
- c_noise = sigma.clone()
31
- return c_skip, c_out, c_in, c_noise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/denoiser_weighting.py DELETED
@@ -1,24 +0,0 @@
1
- import torch
2
-
3
- class UnitWeighting:
4
- def __call__(self, sigma):
5
- return torch.ones_like(sigma, device=sigma.device)
6
-
7
-
8
- class EDMWeighting:
9
- def __init__(self, sigma_data=0.5):
10
- self.sigma_data = sigma_data
11
-
12
- def __call__(self, sigma):
13
- return (sigma**2 + self.sigma_data**2) / (sigma * self.sigma_data) ** 2
14
-
15
-
16
- class VWeighting(EDMWeighting):
17
- def __init__(self):
18
- super().__init__(sigma_data=1.0)
19
-
20
-
21
- class EpsWeighting:
22
- def __call__(self, sigma):
23
- return sigma**-2
24
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/discretizer.py DELETED
@@ -1,69 +0,0 @@
1
- from abc import abstractmethod
2
- from functools import partial
3
-
4
- import numpy as np
5
- import torch
6
-
7
- from ...modules.diffusionmodules.util import make_beta_schedule
8
- from ...util import append_zero
9
-
10
-
11
- def generate_roughly_equally_spaced_steps(
12
- num_substeps: int, max_step: int
13
- ) -> np.ndarray:
14
- return np.linspace(max_step - 1, 0, num_substeps, endpoint=False).astype(int)[::-1]
15
-
16
-
17
- class Discretization:
18
- def __call__(self, n, do_append_zero=True, device="cpu", flip=False):
19
- sigmas = self.get_sigmas(n, device=device)
20
- sigmas = append_zero(sigmas) if do_append_zero else sigmas
21
- return sigmas if not flip else torch.flip(sigmas, (0,))
22
-
23
- @abstractmethod
24
- def get_sigmas(self, n, device):
25
- pass
26
-
27
-
28
- class EDMDiscretization(Discretization):
29
- def __init__(self, sigma_min=0.02, sigma_max=80.0, rho=7.0):
30
- self.sigma_min = sigma_min
31
- self.sigma_max = sigma_max
32
- self.rho = rho
33
-
34
- def get_sigmas(self, n, device="cpu"):
35
- ramp = torch.linspace(0, 1, n, device=device)
36
- min_inv_rho = self.sigma_min ** (1 / self.rho)
37
- max_inv_rho = self.sigma_max ** (1 / self.rho)
38
- sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** self.rho
39
- return sigmas
40
-
41
-
42
- class LegacyDDPMDiscretization(Discretization):
43
- def __init__(
44
- self,
45
- linear_start=0.00085,
46
- linear_end=0.0120,
47
- num_timesteps=1000,
48
- ):
49
- super().__init__()
50
- self.num_timesteps = num_timesteps
51
- betas = make_beta_schedule(
52
- "linear", num_timesteps, linear_start=linear_start, linear_end=linear_end
53
- )
54
- alphas = 1.0 - betas
55
- self.alphas_cumprod = np.cumprod(alphas, axis=0)
56
- self.to_torch = partial(torch.tensor, dtype=torch.float32)
57
-
58
- def get_sigmas(self, n, device="cpu"):
59
- if n < self.num_timesteps:
60
- timesteps = generate_roughly_equally_spaced_steps(n, self.num_timesteps)
61
- alphas_cumprod = self.alphas_cumprod[timesteps]
62
- elif n == self.num_timesteps:
63
- alphas_cumprod = self.alphas_cumprod
64
- else:
65
- raise ValueError
66
-
67
- to_torch = partial(torch.tensor, dtype=torch.float32, device=device)
68
- sigmas = to_torch((1 - alphas_cumprod) / alphas_cumprod) ** 0.5
69
- return torch.flip(sigmas, (0,))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/guiders.py DELETED
@@ -1,88 +0,0 @@
1
- from functools import partial
2
-
3
- import torch
4
-
5
- from ...util import default, instantiate_from_config
6
-
7
-
8
- class VanillaCFG:
9
- """
10
- implements parallelized CFG
11
- """
12
-
13
- def __init__(self, scale, dyn_thresh_config=None):
14
- scale_schedule = lambda scale, sigma: scale # independent of step
15
- self.scale_schedule = partial(scale_schedule, scale)
16
- self.dyn_thresh = instantiate_from_config(
17
- default(
18
- dyn_thresh_config,
19
- {
20
- "target": "sgm.modules.diffusionmodules.sampling_utils.NoDynamicThresholding"
21
- },
22
- )
23
- )
24
-
25
- def __call__(self, x, sigma):
26
- x_u, x_c = x.chunk(2)
27
- scale_value = self.scale_schedule(sigma)
28
- x_pred = self.dyn_thresh(x_u, x_c, scale_value)
29
- return x_pred
30
-
31
- def prepare_inputs(self, x, s, c, uc):
32
- c_out = dict()
33
-
34
- for k in c:
35
- if k in ["vector", "crossattn", "concat", "control", 'control_vector', 'mask_x']:
36
- c_out[k] = torch.cat((uc[k], c[k]), 0)
37
- else:
38
- assert c[k] == uc[k]
39
- c_out[k] = c[k]
40
- return torch.cat([x] * 2), torch.cat([s] * 2), c_out
41
-
42
-
43
-
44
- class LinearCFG:
45
- def __init__(self, scale, scale_min=None, dyn_thresh_config=None):
46
- if scale_min is None:
47
- scale_min = scale
48
- scale_schedule = lambda scale, scale_min, sigma: (scale - scale_min) * sigma / 14.6146 + scale_min
49
- self.scale_schedule = partial(scale_schedule, scale, scale_min)
50
- self.dyn_thresh = instantiate_from_config(
51
- default(
52
- dyn_thresh_config,
53
- {
54
- "target": "sgm.modules.diffusionmodules.sampling_utils.NoDynamicThresholding"
55
- },
56
- )
57
- )
58
-
59
- def __call__(self, x, sigma):
60
- x_u, x_c = x.chunk(2)
61
- scale_value = self.scale_schedule(sigma)
62
- x_pred = self.dyn_thresh(x_u, x_c, scale_value)
63
- return x_pred
64
-
65
- def prepare_inputs(self, x, s, c, uc):
66
- c_out = dict()
67
-
68
- for k in c:
69
- if k in ["vector", "crossattn", "concat", "control", 'control_vector', 'mask_x']:
70
- c_out[k] = torch.cat((uc[k], c[k]), 0)
71
- else:
72
- assert c[k] == uc[k]
73
- c_out[k] = c[k]
74
- return torch.cat([x] * 2), torch.cat([s] * 2), c_out
75
-
76
-
77
-
78
- class IdentityGuider:
79
- def __call__(self, x, sigma):
80
- return x
81
-
82
- def prepare_inputs(self, x, s, c, uc):
83
- c_out = dict()
84
-
85
- for k in c:
86
- c_out[k] = c[k]
87
-
88
- return x, s, c_out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/loss.py DELETED
@@ -1,69 +0,0 @@
1
- from typing import List, Optional, Union
2
-
3
- import torch
4
- import torch.nn as nn
5
- from omegaconf import ListConfig
6
-
7
- from ...util import append_dims, instantiate_from_config
8
- from ...modules.autoencoding.lpips.loss.lpips import LPIPS
9
-
10
-
11
- class StandardDiffusionLoss(nn.Module):
12
- def __init__(
13
- self,
14
- sigma_sampler_config,
15
- type="l2",
16
- offset_noise_level=0.0,
17
- batch2model_keys: Optional[Union[str, List[str], ListConfig]] = None,
18
- ):
19
- super().__init__()
20
-
21
- assert type in ["l2", "l1", "lpips"]
22
-
23
- self.sigma_sampler = instantiate_from_config(sigma_sampler_config)
24
-
25
- self.type = type
26
- self.offset_noise_level = offset_noise_level
27
-
28
- if type == "lpips":
29
- self.lpips = LPIPS().eval()
30
-
31
- if not batch2model_keys:
32
- batch2model_keys = []
33
-
34
- if isinstance(batch2model_keys, str):
35
- batch2model_keys = [batch2model_keys]
36
-
37
- self.batch2model_keys = set(batch2model_keys)
38
-
39
- def __call__(self, network, denoiser, conditioner, input, batch):
40
- cond = conditioner(batch)
41
- additional_model_inputs = {
42
- key: batch[key] for key in self.batch2model_keys.intersection(batch)
43
- }
44
-
45
- sigmas = self.sigma_sampler(input.shape[0]).to(input.device)
46
- noise = torch.randn_like(input)
47
- if self.offset_noise_level > 0.0:
48
- noise = noise + self.offset_noise_level * append_dims(
49
- torch.randn(input.shape[0], device=input.device), input.ndim
50
- )
51
- noised_input = input + noise * append_dims(sigmas, input.ndim)
52
- model_output = denoiser(
53
- network, noised_input, sigmas, cond, **additional_model_inputs
54
- )
55
- w = append_dims(denoiser.w(sigmas), input.ndim)
56
- return self.get_loss(model_output, input, w)
57
-
58
- def get_loss(self, model_output, target, w):
59
- if self.type == "l2":
60
- return torch.mean(
61
- (w * (model_output - target) ** 2).reshape(target.shape[0], -1), 1
62
- )
63
- elif self.type == "l1":
64
- return torch.mean(
65
- (w * (model_output - target).abs()).reshape(target.shape[0], -1), 1
66
- )
67
- elif self.type == "lpips":
68
- loss = self.lpips(model_output, target).reshape(-1)
69
- return loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/model.py DELETED
@@ -1,743 +0,0 @@
1
- # pytorch_diffusion + derived encoder decoder
2
- import math
3
- from typing import Any, Callable, Optional
4
-
5
- import numpy as np
6
- import torch
7
- import torch.nn as nn
8
- from einops import rearrange
9
- from packaging import version
10
-
11
- try:
12
- import xformers
13
- import xformers.ops
14
-
15
- XFORMERS_IS_AVAILABLE = True
16
- except:
17
- XFORMERS_IS_AVAILABLE = False
18
- print("no module 'xformers'. Processing without...")
19
-
20
- from ...modules.attention import LinearAttention, MemoryEfficientCrossAttention
21
-
22
-
23
- def get_timestep_embedding(timesteps, embedding_dim):
24
- """
25
- This matches the implementation in Denoising Diffusion Probabilistic Models:
26
- From Fairseq.
27
- Build sinusoidal embeddings.
28
- This matches the implementation in tensor2tensor, but differs slightly
29
- from the description in Section 3.5 of "Attention Is All You Need".
30
- """
31
- assert len(timesteps.shape) == 1
32
-
33
- half_dim = embedding_dim // 2
34
- emb = math.log(10000) / (half_dim - 1)
35
- emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
36
- emb = emb.to(device=timesteps.device)
37
- emb = timesteps.float()[:, None] * emb[None, :]
38
- emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
39
- if embedding_dim % 2 == 1: # zero pad
40
- emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
41
- return emb
42
-
43
-
44
- def nonlinearity(x):
45
- # swish
46
- return x * torch.sigmoid(x)
47
-
48
-
49
- def Normalize(in_channels, num_groups=32):
50
- return torch.nn.GroupNorm(
51
- num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True
52
- )
53
-
54
-
55
- class Upsample(nn.Module):
56
- def __init__(self, in_channels, with_conv):
57
- super().__init__()
58
- self.with_conv = with_conv
59
- if self.with_conv:
60
- self.conv = torch.nn.Conv2d(
61
- in_channels, in_channels, kernel_size=3, stride=1, padding=1
62
- )
63
-
64
- def forward(self, x):
65
- x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
66
- if self.with_conv:
67
- x = self.conv(x)
68
- return x
69
-
70
-
71
- class Downsample(nn.Module):
72
- def __init__(self, in_channels, with_conv):
73
- super().__init__()
74
- self.with_conv = with_conv
75
- if self.with_conv:
76
- # no asymmetric padding in torch conv, must do it ourselves
77
- self.conv = torch.nn.Conv2d(
78
- in_channels, in_channels, kernel_size=3, stride=2, padding=0
79
- )
80
-
81
- def forward(self, x):
82
- if self.with_conv:
83
- pad = (0, 1, 0, 1)
84
- x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
85
- x = self.conv(x)
86
- else:
87
- x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
88
- return x
89
-
90
-
91
- class ResnetBlock(nn.Module):
92
- def __init__(
93
- self,
94
- *,
95
- in_channels,
96
- out_channels=None,
97
- conv_shortcut=False,
98
- dropout,
99
- temb_channels=512,
100
- ):
101
- super().__init__()
102
- self.in_channels = in_channels
103
- out_channels = in_channels if out_channels is None else out_channels
104
- self.out_channels = out_channels
105
- self.use_conv_shortcut = conv_shortcut
106
-
107
- self.norm1 = Normalize(in_channels)
108
- self.conv1 = torch.nn.Conv2d(
109
- in_channels, out_channels, kernel_size=3, stride=1, padding=1
110
- )
111
- if temb_channels > 0:
112
- self.temb_proj = torch.nn.Linear(temb_channels, out_channels)
113
- self.norm2 = Normalize(out_channels)
114
- self.dropout = torch.nn.Dropout(dropout)
115
- self.conv2 = torch.nn.Conv2d(
116
- out_channels, out_channels, kernel_size=3, stride=1, padding=1
117
- )
118
- if self.in_channels != self.out_channels:
119
- if self.use_conv_shortcut:
120
- self.conv_shortcut = torch.nn.Conv2d(
121
- in_channels, out_channels, kernel_size=3, stride=1, padding=1
122
- )
123
- else:
124
- self.nin_shortcut = torch.nn.Conv2d(
125
- in_channels, out_channels, kernel_size=1, stride=1, padding=0
126
- )
127
-
128
- def forward(self, x, temb):
129
- h = x
130
- h = self.norm1(h)
131
- h = nonlinearity(h)
132
- h = self.conv1(h)
133
-
134
- if temb is not None:
135
- h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None]
136
-
137
- h = self.norm2(h)
138
- h = nonlinearity(h)
139
- h = self.dropout(h)
140
- h = self.conv2(h)
141
-
142
- if self.in_channels != self.out_channels:
143
- if self.use_conv_shortcut:
144
- x = self.conv_shortcut(x)
145
- else:
146
- x = self.nin_shortcut(x)
147
-
148
- return x + h
149
-
150
-
151
- class LinAttnBlock(LinearAttention):
152
- """to match AttnBlock usage"""
153
-
154
- def __init__(self, in_channels):
155
- super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
156
-
157
-
158
- class AttnBlock(nn.Module):
159
- def __init__(self, in_channels):
160
- super().__init__()
161
- self.in_channels = in_channels
162
-
163
- self.norm = Normalize(in_channels)
164
- self.q = torch.nn.Conv2d(
165
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
166
- )
167
- self.k = torch.nn.Conv2d(
168
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
169
- )
170
- self.v = torch.nn.Conv2d(
171
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
172
- )
173
- self.proj_out = torch.nn.Conv2d(
174
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
175
- )
176
-
177
- def attention(self, h_: torch.Tensor) -> torch.Tensor:
178
- h_ = self.norm(h_)
179
- q = self.q(h_)
180
- k = self.k(h_)
181
- v = self.v(h_)
182
-
183
- b, c, h, w = q.shape
184
- q, k, v = map(
185
- lambda x: rearrange(x, "b c h w -> b 1 (h w) c").contiguous(), (q, k, v)
186
- )
187
- h_ = torch.nn.functional.scaled_dot_product_attention(
188
- q, k, v
189
- ) # scale is dim ** -0.5 per default
190
- # compute attention
191
-
192
- return rearrange(h_, "b 1 (h w) c -> b c h w", h=h, w=w, c=c, b=b)
193
-
194
- def forward(self, x, **kwargs):
195
- h_ = x
196
- h_ = self.attention(h_)
197
- h_ = self.proj_out(h_)
198
- return x + h_
199
-
200
-
201
- class MemoryEfficientAttnBlock(nn.Module):
202
- """
203
- Uses xformers efficient implementation,
204
- see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
205
- Note: this is a single-head self-attention operation
206
- """
207
-
208
- #
209
- def __init__(self, in_channels):
210
- super().__init__()
211
- self.in_channels = in_channels
212
-
213
- self.norm = Normalize(in_channels)
214
- self.q = torch.nn.Conv2d(
215
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
216
- )
217
- self.k = torch.nn.Conv2d(
218
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
219
- )
220
- self.v = torch.nn.Conv2d(
221
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
222
- )
223
- self.proj_out = torch.nn.Conv2d(
224
- in_channels, in_channels, kernel_size=1, stride=1, padding=0
225
- )
226
- self.attention_op: Optional[Any] = None
227
-
228
- def attention(self, h_: torch.Tensor) -> torch.Tensor:
229
- h_ = self.norm(h_)
230
- q = self.q(h_)
231
- k = self.k(h_)
232
- v = self.v(h_)
233
-
234
- # compute attention
235
- B, C, H, W = q.shape
236
- q, k, v = map(lambda x: rearrange(x, "b c h w -> b (h w) c"), (q, k, v))
237
-
238
- q, k, v = map(
239
- lambda t: t.unsqueeze(3)
240
- .reshape(B, t.shape[1], 1, C)
241
- .permute(0, 2, 1, 3)
242
- .reshape(B * 1, t.shape[1], C)
243
- .contiguous(),
244
- (q, k, v),
245
- )
246
- out = xformers.ops.memory_efficient_attention(
247
- q, k, v, attn_bias=None, op=self.attention_op
248
- )
249
-
250
- out = (
251
- out.unsqueeze(0)
252
- .reshape(B, 1, out.shape[1], C)
253
- .permute(0, 2, 1, 3)
254
- .reshape(B, out.shape[1], C)
255
- )
256
- return rearrange(out, "b (h w) c -> b c h w", b=B, h=H, w=W, c=C)
257
-
258
- def forward(self, x, **kwargs):
259
- h_ = x
260
- h_ = self.attention(h_)
261
- h_ = self.proj_out(h_)
262
- return x + h_
263
-
264
-
265
- class MemoryEfficientCrossAttentionWrapper(MemoryEfficientCrossAttention):
266
- def forward(self, x, context=None, mask=None, **unused_kwargs):
267
- b, c, h, w = x.shape
268
- x = rearrange(x, "b c h w -> b (h w) c")
269
- out = super().forward(x, context=context, mask=mask)
270
- out = rearrange(out, "b (h w) c -> b c h w", h=h, w=w, c=c)
271
- return x + out
272
-
273
-
274
- def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None):
275
- assert attn_type in [
276
- "vanilla",
277
- "vanilla-xformers",
278
- "memory-efficient-cross-attn",
279
- "linear",
280
- "none",
281
- ], f"attn_type {attn_type} unknown"
282
- if (
283
- version.parse(torch.__version__) < version.parse("2.0.0")
284
- and attn_type != "none"
285
- ):
286
- assert XFORMERS_IS_AVAILABLE, (
287
- f"We do not support vanilla attention in {torch.__version__} anymore, "
288
- f"as it is too expensive. Please install xformers via e.g. 'pip install xformers==0.0.16'"
289
- )
290
- attn_type = "vanilla-xformers"
291
- print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
292
- if attn_type == "vanilla":
293
- assert attn_kwargs is None
294
- return AttnBlock(in_channels)
295
- elif attn_type == "vanilla-xformers":
296
- print(f"building MemoryEfficientAttnBlock with {in_channels} in_channels...")
297
- return MemoryEfficientAttnBlock(in_channels)
298
- elif type == "memory-efficient-cross-attn":
299
- attn_kwargs["query_dim"] = in_channels
300
- return MemoryEfficientCrossAttentionWrapper(**attn_kwargs)
301
- elif attn_type == "none":
302
- return nn.Identity(in_channels)
303
- else:
304
- return LinAttnBlock(in_channels)
305
-
306
-
307
- class Model(nn.Module):
308
- def __init__(
309
- self,
310
- *,
311
- ch,
312
- out_ch,
313
- ch_mult=(1, 2, 4, 8),
314
- num_res_blocks,
315
- attn_resolutions,
316
- dropout=0.0,
317
- resamp_with_conv=True,
318
- in_channels,
319
- resolution,
320
- use_timestep=True,
321
- use_linear_attn=False,
322
- attn_type="vanilla",
323
- ):
324
- super().__init__()
325
- if use_linear_attn:
326
- attn_type = "linear"
327
- self.ch = ch
328
- self.temb_ch = self.ch * 4
329
- self.num_resolutions = len(ch_mult)
330
- self.num_res_blocks = num_res_blocks
331
- self.resolution = resolution
332
- self.in_channels = in_channels
333
-
334
- self.use_timestep = use_timestep
335
- if self.use_timestep:
336
- # timestep embedding
337
- self.temb = nn.Module()
338
- self.temb.dense = nn.ModuleList(
339
- [
340
- torch.nn.Linear(self.ch, self.temb_ch),
341
- torch.nn.Linear(self.temb_ch, self.temb_ch),
342
- ]
343
- )
344
-
345
- # downsampling
346
- self.conv_in = torch.nn.Conv2d(
347
- in_channels, self.ch, kernel_size=3, stride=1, padding=1
348
- )
349
-
350
- curr_res = resolution
351
- in_ch_mult = (1,) + tuple(ch_mult)
352
- self.down = nn.ModuleList()
353
- for i_level in range(self.num_resolutions):
354
- block = nn.ModuleList()
355
- attn = nn.ModuleList()
356
- block_in = ch * in_ch_mult[i_level]
357
- block_out = ch * ch_mult[i_level]
358
- for i_block in range(self.num_res_blocks):
359
- block.append(
360
- ResnetBlock(
361
- in_channels=block_in,
362
- out_channels=block_out,
363
- temb_channels=self.temb_ch,
364
- dropout=dropout,
365
- )
366
- )
367
- block_in = block_out
368
- if curr_res in attn_resolutions:
369
- attn.append(make_attn(block_in, attn_type=attn_type))
370
- down = nn.Module()
371
- down.block = block
372
- down.attn = attn
373
- if i_level != self.num_resolutions - 1:
374
- down.downsample = Downsample(block_in, resamp_with_conv)
375
- curr_res = curr_res // 2
376
- self.down.append(down)
377
-
378
- # middle
379
- self.mid = nn.Module()
380
- self.mid.block_1 = ResnetBlock(
381
- in_channels=block_in,
382
- out_channels=block_in,
383
- temb_channels=self.temb_ch,
384
- dropout=dropout,
385
- )
386
- self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
387
- self.mid.block_2 = ResnetBlock(
388
- in_channels=block_in,
389
- out_channels=block_in,
390
- temb_channels=self.temb_ch,
391
- dropout=dropout,
392
- )
393
-
394
- # upsampling
395
- self.up = nn.ModuleList()
396
- for i_level in reversed(range(self.num_resolutions)):
397
- block = nn.ModuleList()
398
- attn = nn.ModuleList()
399
- block_out = ch * ch_mult[i_level]
400
- skip_in = ch * ch_mult[i_level]
401
- for i_block in range(self.num_res_blocks + 1):
402
- if i_block == self.num_res_blocks:
403
- skip_in = ch * in_ch_mult[i_level]
404
- block.append(
405
- ResnetBlock(
406
- in_channels=block_in + skip_in,
407
- out_channels=block_out,
408
- temb_channels=self.temb_ch,
409
- dropout=dropout,
410
- )
411
- )
412
- block_in = block_out
413
- if curr_res in attn_resolutions:
414
- attn.append(make_attn(block_in, attn_type=attn_type))
415
- up = nn.Module()
416
- up.block = block
417
- up.attn = attn
418
- if i_level != 0:
419
- up.upsample = Upsample(block_in, resamp_with_conv)
420
- curr_res = curr_res * 2
421
- self.up.insert(0, up) # prepend to get consistent order
422
-
423
- # end
424
- self.norm_out = Normalize(block_in)
425
- self.conv_out = torch.nn.Conv2d(
426
- block_in, out_ch, kernel_size=3, stride=1, padding=1
427
- )
428
-
429
- def forward(self, x, t=None, context=None):
430
- # assert x.shape[2] == x.shape[3] == self.resolution
431
- if context is not None:
432
- # assume aligned context, cat along channel axis
433
- x = torch.cat((x, context), dim=1)
434
- if self.use_timestep:
435
- # timestep embedding
436
- assert t is not None
437
- temb = get_timestep_embedding(t, self.ch)
438
- temb = self.temb.dense[0](temb)
439
- temb = nonlinearity(temb)
440
- temb = self.temb.dense[1](temb)
441
- else:
442
- temb = None
443
-
444
- # downsampling
445
- hs = [self.conv_in(x)]
446
- for i_level in range(self.num_resolutions):
447
- for i_block in range(self.num_res_blocks):
448
- h = self.down[i_level].block[i_block](hs[-1], temb)
449
- if len(self.down[i_level].attn) > 0:
450
- h = self.down[i_level].attn[i_block](h)
451
- hs.append(h)
452
- if i_level != self.num_resolutions - 1:
453
- hs.append(self.down[i_level].downsample(hs[-1]))
454
-
455
- # middle
456
- h = hs[-1]
457
- h = self.mid.block_1(h, temb)
458
- h = self.mid.attn_1(h)
459
- h = self.mid.block_2(h, temb)
460
-
461
- # upsampling
462
- for i_level in reversed(range(self.num_resolutions)):
463
- for i_block in range(self.num_res_blocks + 1):
464
- h = self.up[i_level].block[i_block](
465
- torch.cat([h, hs.pop()], dim=1), temb
466
- )
467
- if len(self.up[i_level].attn) > 0:
468
- h = self.up[i_level].attn[i_block](h)
469
- if i_level != 0:
470
- h = self.up[i_level].upsample(h)
471
-
472
- # end
473
- h = self.norm_out(h)
474
- h = nonlinearity(h)
475
- h = self.conv_out(h)
476
- return h
477
-
478
- def get_last_layer(self):
479
- return self.conv_out.weight
480
-
481
-
482
- class Encoder(nn.Module):
483
- def __init__(
484
- self,
485
- *,
486
- ch,
487
- out_ch,
488
- ch_mult=(1, 2, 4, 8),
489
- num_res_blocks,
490
- attn_resolutions,
491
- dropout=0.0,
492
- resamp_with_conv=True,
493
- in_channels,
494
- resolution,
495
- z_channels,
496
- double_z=True,
497
- use_linear_attn=False,
498
- attn_type="vanilla",
499
- **ignore_kwargs,
500
- ):
501
- super().__init__()
502
- if use_linear_attn:
503
- attn_type = "linear"
504
- self.ch = ch
505
- self.temb_ch = 0
506
- self.num_resolutions = len(ch_mult)
507
- self.num_res_blocks = num_res_blocks
508
- self.resolution = resolution
509
- self.in_channels = in_channels
510
-
511
- # downsampling
512
- self.conv_in = torch.nn.Conv2d(
513
- in_channels, self.ch, kernel_size=3, stride=1, padding=1
514
- )
515
-
516
- curr_res = resolution
517
- in_ch_mult = (1,) + tuple(ch_mult)
518
- self.in_ch_mult = in_ch_mult
519
- self.down = nn.ModuleList()
520
- for i_level in range(self.num_resolutions):
521
- block = nn.ModuleList()
522
- attn = nn.ModuleList()
523
- block_in = ch * in_ch_mult[i_level]
524
- block_out = ch * ch_mult[i_level]
525
- for i_block in range(self.num_res_blocks):
526
- block.append(
527
- ResnetBlock(
528
- in_channels=block_in,
529
- out_channels=block_out,
530
- temb_channels=self.temb_ch,
531
- dropout=dropout,
532
- )
533
- )
534
- block_in = block_out
535
- if curr_res in attn_resolutions:
536
- attn.append(make_attn(block_in, attn_type=attn_type))
537
- down = nn.Module()
538
- down.block = block
539
- down.attn = attn
540
- if i_level != self.num_resolutions - 1:
541
- down.downsample = Downsample(block_in, resamp_with_conv)
542
- curr_res = curr_res // 2
543
- self.down.append(down)
544
-
545
- # middle
546
- self.mid = nn.Module()
547
- self.mid.block_1 = ResnetBlock(
548
- in_channels=block_in,
549
- out_channels=block_in,
550
- temb_channels=self.temb_ch,
551
- dropout=dropout,
552
- )
553
- self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
554
- self.mid.block_2 = ResnetBlock(
555
- in_channels=block_in,
556
- out_channels=block_in,
557
- temb_channels=self.temb_ch,
558
- dropout=dropout,
559
- )
560
-
561
- # end
562
- self.norm_out = Normalize(block_in)
563
- self.conv_out = torch.nn.Conv2d(
564
- block_in,
565
- 2 * z_channels if double_z else z_channels,
566
- kernel_size=3,
567
- stride=1,
568
- padding=1,
569
- )
570
-
571
- def forward(self, x):
572
- # timestep embedding
573
- temb = None
574
-
575
- # downsampling
576
- hs = [self.conv_in(x)]
577
- for i_level in range(self.num_resolutions):
578
- for i_block in range(self.num_res_blocks):
579
- h = self.down[i_level].block[i_block](hs[-1], temb)
580
- if len(self.down[i_level].attn) > 0:
581
- h = self.down[i_level].attn[i_block](h)
582
- hs.append(h)
583
- if i_level != self.num_resolutions - 1:
584
- hs.append(self.down[i_level].downsample(hs[-1]))
585
-
586
- # middle
587
- h = hs[-1]
588
- h = self.mid.block_1(h, temb)
589
- h = self.mid.attn_1(h)
590
- h = self.mid.block_2(h, temb)
591
-
592
- # end
593
- h = self.norm_out(h)
594
- h = nonlinearity(h)
595
- h = self.conv_out(h)
596
- return h
597
-
598
-
599
- class Decoder(nn.Module):
600
- def __init__(
601
- self,
602
- *,
603
- ch,
604
- out_ch,
605
- ch_mult=(1, 2, 4, 8),
606
- num_res_blocks,
607
- attn_resolutions,
608
- dropout=0.0,
609
- resamp_with_conv=True,
610
- in_channels,
611
- resolution,
612
- z_channels,
613
- give_pre_end=False,
614
- tanh_out=False,
615
- use_linear_attn=False,
616
- attn_type="vanilla",
617
- **ignorekwargs,
618
- ):
619
- super().__init__()
620
- if use_linear_attn:
621
- attn_type = "linear"
622
- self.ch = ch
623
- self.temb_ch = 0
624
- self.num_resolutions = len(ch_mult)
625
- self.num_res_blocks = num_res_blocks
626
- self.resolution = resolution
627
- self.in_channels = in_channels
628
- self.give_pre_end = give_pre_end
629
- self.tanh_out = tanh_out
630
-
631
- # compute in_ch_mult, block_in and curr_res at lowest res
632
- in_ch_mult = (1,) + tuple(ch_mult)
633
- block_in = ch * ch_mult[self.num_resolutions - 1]
634
- curr_res = resolution // 2 ** (self.num_resolutions - 1)
635
- self.z_shape = (1, z_channels, curr_res, curr_res)
636
- print(
637
- "Working with z of shape {} = {} dimensions.".format(
638
- self.z_shape, np.prod(self.z_shape)
639
- )
640
- )
641
-
642
- make_attn_cls = self._make_attn()
643
- make_resblock_cls = self._make_resblock()
644
- make_conv_cls = self._make_conv()
645
- # z to block_in
646
- self.conv_in = torch.nn.Conv2d(
647
- z_channels, block_in, kernel_size=3, stride=1, padding=1
648
- )
649
-
650
- # middle
651
- self.mid = nn.Module()
652
- self.mid.block_1 = make_resblock_cls(
653
- in_channels=block_in,
654
- out_channels=block_in,
655
- temb_channels=self.temb_ch,
656
- dropout=dropout,
657
- )
658
- self.mid.attn_1 = make_attn_cls(block_in, attn_type=attn_type)
659
- self.mid.block_2 = make_resblock_cls(
660
- in_channels=block_in,
661
- out_channels=block_in,
662
- temb_channels=self.temb_ch,
663
- dropout=dropout,
664
- )
665
-
666
- # upsampling
667
- self.up = nn.ModuleList()
668
- for i_level in reversed(range(self.num_resolutions)):
669
- block = nn.ModuleList()
670
- attn = nn.ModuleList()
671
- block_out = ch * ch_mult[i_level]
672
- for i_block in range(self.num_res_blocks + 1):
673
- block.append(
674
- make_resblock_cls(
675
- in_channels=block_in,
676
- out_channels=block_out,
677
- temb_channels=self.temb_ch,
678
- dropout=dropout,
679
- )
680
- )
681
- block_in = block_out
682
- if curr_res in attn_resolutions:
683
- attn.append(make_attn_cls(block_in, attn_type=attn_type))
684
- up = nn.Module()
685
- up.block = block
686
- up.attn = attn
687
- if i_level != 0:
688
- up.upsample = Upsample(block_in, resamp_with_conv)
689
- curr_res = curr_res * 2
690
- self.up.insert(0, up) # prepend to get consistent order
691
-
692
- # end
693
- self.norm_out = Normalize(block_in)
694
- self.conv_out = make_conv_cls(
695
- block_in, out_ch, kernel_size=3, stride=1, padding=1
696
- )
697
-
698
- def _make_attn(self) -> Callable:
699
- return make_attn
700
-
701
- def _make_resblock(self) -> Callable:
702
- return ResnetBlock
703
-
704
- def _make_conv(self) -> Callable:
705
- return torch.nn.Conv2d
706
-
707
- def get_last_layer(self, **kwargs):
708
- return self.conv_out.weight
709
-
710
- def forward(self, z, **kwargs):
711
- # assert z.shape[1:] == self.z_shape[1:]
712
- self.last_z_shape = z.shape
713
-
714
- # timestep embedding
715
- temb = None
716
-
717
- # z to block_in
718
- h = self.conv_in(z)
719
-
720
- # middle
721
- h = self.mid.block_1(h, temb, **kwargs)
722
- h = self.mid.attn_1(h, **kwargs)
723
- h = self.mid.block_2(h, temb, **kwargs)
724
-
725
- # upsampling
726
- for i_level in reversed(range(self.num_resolutions)):
727
- for i_block in range(self.num_res_blocks + 1):
728
- h = self.up[i_level].block[i_block](h, temb, **kwargs)
729
- if len(self.up[i_level].attn) > 0:
730
- h = self.up[i_level].attn[i_block](h, **kwargs)
731
- if i_level != 0:
732
- h = self.up[i_level].upsample(h)
733
-
734
- # end
735
- if self.give_pre_end:
736
- return h
737
-
738
- h = self.norm_out(h)
739
- h = nonlinearity(h)
740
- h = self.conv_out(h, **kwargs)
741
- if self.tanh_out:
742
- h = torch.tanh(h)
743
- return h
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/openaimodel.py DELETED
@@ -1,1272 +0,0 @@
1
- import math
2
- from abc import abstractmethod
3
- from functools import partial
4
- from typing import Iterable
5
-
6
- import numpy as np
7
- import torch as th
8
- import torch.nn as nn
9
- import torch.nn.functional as F
10
- # from einops._torch_specific import allow_ops_in_compiled_graph
11
- # allow_ops_in_compiled_graph()
12
- from einops import rearrange
13
-
14
- from ...modules.attention import SpatialTransformer
15
- from ...modules.diffusionmodules.util import (
16
- avg_pool_nd,
17
- checkpoint,
18
- conv_nd,
19
- linear,
20
- normalization,
21
- timestep_embedding,
22
- zero_module,
23
- )
24
- from ...util import default, exists
25
-
26
-
27
- # dummy replace
28
- def convert_module_to_f16(x):
29
- pass
30
-
31
-
32
- def convert_module_to_f32(x):
33
- pass
34
-
35
-
36
- ## go
37
- class AttentionPool2d(nn.Module):
38
- """
39
- Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
40
- """
41
-
42
- def __init__(
43
- self,
44
- spacial_dim: int,
45
- embed_dim: int,
46
- num_heads_channels: int,
47
- output_dim: int = None,
48
- ):
49
- super().__init__()
50
- self.positional_embedding = nn.Parameter(
51
- th.randn(embed_dim, spacial_dim**2 + 1) / embed_dim**0.5
52
- )
53
- self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
54
- self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
55
- self.num_heads = embed_dim // num_heads_channels
56
- self.attention = QKVAttention(self.num_heads)
57
-
58
- def forward(self, x):
59
- b, c, *_spatial = x.shape
60
- x = x.reshape(b, c, -1) # NC(HW)
61
- x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
62
- x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
63
- x = self.qkv_proj(x)
64
- x = self.attention(x)
65
- x = self.c_proj(x)
66
- return x[:, :, 0]
67
-
68
-
69
- class TimestepBlock(nn.Module):
70
- """
71
- Any module where forward() takes timestep embeddings as a second argument.
72
- """
73
-
74
- @abstractmethod
75
- def forward(self, x, emb):
76
- """
77
- Apply the module to `x` given `emb` timestep embeddings.
78
- """
79
-
80
-
81
- class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
82
- """
83
- A sequential module that passes timestep embeddings to the children that
84
- support it as an extra input.
85
- """
86
-
87
- def forward(
88
- self,
89
- x,
90
- emb,
91
- context=None,
92
- skip_time_mix=False,
93
- time_context=None,
94
- num_video_frames=None,
95
- time_context_cat=None,
96
- use_crossframe_attention_in_spatial_layers=False,
97
- ):
98
- for layer in self:
99
- if isinstance(layer, TimestepBlock):
100
- x = layer(x, emb)
101
- elif isinstance(layer, SpatialTransformer):
102
- x = layer(x, context)
103
- else:
104
- x = layer(x)
105
- return x
106
-
107
-
108
- class Upsample(nn.Module):
109
- """
110
- An upsampling layer with an optional convolution.
111
- :param channels: channels in the inputs and outputs.
112
- :param use_conv: a bool determining if a convolution is applied.
113
- :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
114
- upsampling occurs in the inner-two dimensions.
115
- """
116
-
117
- def __init__(
118
- self, channels, use_conv, dims=2, out_channels=None, padding=1, third_up=False
119
- ):
120
- super().__init__()
121
- self.channels = channels
122
- self.out_channels = out_channels or channels
123
- self.use_conv = use_conv
124
- self.dims = dims
125
- self.third_up = third_up
126
- if use_conv:
127
- self.conv = conv_nd(
128
- dims, self.channels, self.out_channels, 3, padding=padding
129
- )
130
-
131
- def forward(self, x):
132
- # support fp32 only
133
- _dtype = x.dtype
134
- x = x.to(th.float32)
135
-
136
- assert x.shape[1] == self.channels
137
- if self.dims == 3:
138
- t_factor = 1 if not self.third_up else 2
139
- x = F.interpolate(
140
- x,
141
- (t_factor * x.shape[2], x.shape[3] * 2, x.shape[4] * 2),
142
- mode="nearest",
143
- )
144
- else:
145
- x = F.interpolate(x, scale_factor=2, mode="nearest")
146
-
147
- x = x.to(_dtype) # support fp32 only
148
-
149
- if self.use_conv:
150
- x = self.conv(x)
151
- return x
152
-
153
-
154
- class TransposedUpsample(nn.Module):
155
- "Learned 2x upsampling without padding"
156
-
157
- def __init__(self, channels, out_channels=None, ks=5):
158
- super().__init__()
159
- self.channels = channels
160
- self.out_channels = out_channels or channels
161
-
162
- self.up = nn.ConvTranspose2d(
163
- self.channels, self.out_channels, kernel_size=ks, stride=2
164
- )
165
-
166
- def forward(self, x):
167
- return self.up(x)
168
-
169
-
170
- class Downsample(nn.Module):
171
- """
172
- A downsampling layer with an optional convolution.
173
- :param channels: channels in the inputs and outputs.
174
- :param use_conv: a bool determining if a convolution is applied.
175
- :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
176
- downsampling occurs in the inner-two dimensions.
177
- """
178
-
179
- def __init__(
180
- self, channels, use_conv, dims=2, out_channels=None, padding=1, third_down=False
181
- ):
182
- super().__init__()
183
- self.channels = channels
184
- self.out_channels = out_channels or channels
185
- self.use_conv = use_conv
186
- self.dims = dims
187
- stride = 2 if dims != 3 else ((1, 2, 2) if not third_down else (2, 2, 2))
188
- if use_conv:
189
- print(f"Building a Downsample layer with {dims} dims.")
190
- print(
191
- f" --> settings are: \n in-chn: {self.channels}, out-chn: {self.out_channels}, "
192
- f"kernel-size: 3, stride: {stride}, padding: {padding}"
193
- )
194
- if dims == 3:
195
- print(f" --> Downsampling third axis (time): {third_down}")
196
- self.op = conv_nd(
197
- dims,
198
- self.channels,
199
- self.out_channels,
200
- 3,
201
- stride=stride,
202
- padding=padding,
203
- )
204
- else:
205
- assert self.channels == self.out_channels
206
- self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
207
-
208
- def forward(self, x):
209
- assert x.shape[1] == self.channels
210
- return self.op(x)
211
-
212
-
213
- class ResBlock(TimestepBlock):
214
- """
215
- A residual block that can optionally change the number of channels.
216
- :param channels: the number of input channels.
217
- :param emb_channels: the number of timestep embedding channels.
218
- :param dropout: the rate of dropout.
219
- :param out_channels: if specified, the number of out channels.
220
- :param use_conv: if True and out_channels is specified, use a spatial
221
- convolution instead of a smaller 1x1 convolution to change the
222
- channels in the skip connection.
223
- :param dims: determines if the signal is 1D, 2D, or 3D.
224
- :param use_checkpoint: if True, use gradient checkpointing on this module.
225
- :param up: if True, use this block for upsampling.
226
- :param down: if True, use this block for downsampling.
227
- """
228
-
229
- def __init__(
230
- self,
231
- channels,
232
- emb_channels,
233
- dropout,
234
- out_channels=None,
235
- use_conv=False,
236
- use_scale_shift_norm=False,
237
- dims=2,
238
- use_checkpoint=False,
239
- up=False,
240
- down=False,
241
- kernel_size=3,
242
- exchange_temb_dims=False,
243
- skip_t_emb=False,
244
- ):
245
- super().__init__()
246
- self.channels = channels
247
- self.emb_channels = emb_channels
248
- self.dropout = dropout
249
- self.out_channels = out_channels or channels
250
- self.use_conv = use_conv
251
- self.use_checkpoint = use_checkpoint
252
- self.use_scale_shift_norm = use_scale_shift_norm
253
- self.exchange_temb_dims = exchange_temb_dims
254
-
255
- if isinstance(kernel_size, Iterable):
256
- padding = [k // 2 for k in kernel_size]
257
- else:
258
- padding = kernel_size // 2
259
-
260
- self.in_layers = nn.Sequential(
261
- normalization(channels),
262
- nn.SiLU(),
263
- conv_nd(dims, channels, self.out_channels, kernel_size, padding=padding),
264
- )
265
-
266
- self.updown = up or down
267
-
268
- if up:
269
- self.h_upd = Upsample(channels, False, dims)
270
- self.x_upd = Upsample(channels, False, dims)
271
- elif down:
272
- self.h_upd = Downsample(channels, False, dims)
273
- self.x_upd = Downsample(channels, False, dims)
274
- else:
275
- self.h_upd = self.x_upd = nn.Identity()
276
-
277
- self.skip_t_emb = skip_t_emb
278
- self.emb_out_channels = (
279
- 2 * self.out_channels if use_scale_shift_norm else self.out_channels
280
- )
281
- if self.skip_t_emb:
282
- print(f"Skipping timestep embedding in {self.__class__.__name__}")
283
- assert not self.use_scale_shift_norm
284
- self.emb_layers = None
285
- self.exchange_temb_dims = False
286
- else:
287
- self.emb_layers = nn.Sequential(
288
- nn.SiLU(),
289
- linear(
290
- emb_channels,
291
- self.emb_out_channels,
292
- ),
293
- )
294
-
295
- self.out_layers = nn.Sequential(
296
- normalization(self.out_channels),
297
- nn.SiLU(),
298
- nn.Dropout(p=dropout),
299
- zero_module(
300
- conv_nd(
301
- dims,
302
- self.out_channels,
303
- self.out_channels,
304
- kernel_size,
305
- padding=padding,
306
- )
307
- ),
308
- )
309
-
310
- if self.out_channels == channels:
311
- self.skip_connection = nn.Identity()
312
- elif use_conv:
313
- self.skip_connection = conv_nd(
314
- dims, channels, self.out_channels, kernel_size, padding=padding
315
- )
316
- else:
317
- self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
318
-
319
- def forward(self, x, emb):
320
- """
321
- Apply the block to a Tensor, conditioned on a timestep embedding.
322
- :param x: an [N x C x ...] Tensor of features.
323
- :param emb: an [N x emb_channels] Tensor of timestep embeddings.
324
- :return: an [N x C x ...] Tensor of outputs.
325
- """
326
- return checkpoint(
327
- self._forward, (x, emb), self.parameters(), self.use_checkpoint
328
- )
329
-
330
- def _forward(self, x, emb):
331
- if self.updown:
332
- in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
333
- h = in_rest(x)
334
- h = self.h_upd(h)
335
- x = self.x_upd(x)
336
- h = in_conv(h)
337
- else:
338
- h = self.in_layers(x)
339
-
340
- if self.skip_t_emb:
341
- emb_out = th.zeros_like(h)
342
- else:
343
- emb_out = self.emb_layers(emb).type(h.dtype)
344
- while len(emb_out.shape) < len(h.shape):
345
- emb_out = emb_out[..., None]
346
- if self.use_scale_shift_norm:
347
- out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
348
- scale, shift = th.chunk(emb_out, 2, dim=1)
349
- h = out_norm(h) * (1 + scale) + shift
350
- h = out_rest(h)
351
- else:
352
- if self.exchange_temb_dims:
353
- emb_out = rearrange(emb_out, "b t c ... -> b c t ...")
354
- h = h + emb_out
355
- h = self.out_layers(h)
356
- return self.skip_connection(x) + h
357
-
358
-
359
- class AttentionBlock(nn.Module):
360
- """
361
- An attention block that allows spatial positions to attend to each other.
362
- Originally ported from here, but adapted to the N-d case.
363
- https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
364
- """
365
-
366
- def __init__(
367
- self,
368
- channels,
369
- num_heads=1,
370
- num_head_channels=-1,
371
- use_checkpoint=False,
372
- use_new_attention_order=False,
373
- ):
374
- super().__init__()
375
- self.channels = channels
376
- if num_head_channels == -1:
377
- self.num_heads = num_heads
378
- else:
379
- assert (
380
- channels % num_head_channels == 0
381
- ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
382
- self.num_heads = channels // num_head_channels
383
- self.use_checkpoint = use_checkpoint
384
- self.norm = normalization(channels)
385
- self.qkv = conv_nd(1, channels, channels * 3, 1)
386
- if use_new_attention_order:
387
- # split qkv before split heads
388
- self.attention = QKVAttention(self.num_heads)
389
- else:
390
- # split heads before split qkv
391
- self.attention = QKVAttentionLegacy(self.num_heads)
392
-
393
- self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
394
-
395
- def forward(self, x, **kwargs):
396
- # TODO add crossframe attention and use mixed checkpoint
397
- return checkpoint(
398
- self._forward, (x,), self.parameters(), True
399
- ) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
400
- # return pt_checkpoint(self._forward, x) # pytorch
401
-
402
- def _forward(self, x):
403
- b, c, *spatial = x.shape
404
- x = x.reshape(b, c, -1)
405
- qkv = self.qkv(self.norm(x))
406
- h = self.attention(qkv)
407
- h = self.proj_out(h)
408
- return (x + h).reshape(b, c, *spatial)
409
-
410
-
411
- def count_flops_attn(model, _x, y):
412
- """
413
- A counter for the `thop` package to count the operations in an
414
- attention operation.
415
- Meant to be used like:
416
- macs, params = thop.profile(
417
- model,
418
- inputs=(inputs, timestamps),
419
- custom_ops={QKVAttention: QKVAttention.count_flops},
420
- )
421
- """
422
- b, c, *spatial = y[0].shape
423
- num_spatial = int(np.prod(spatial))
424
- # We perform two matmuls with the same number of ops.
425
- # The first computes the weight matrix, the second computes
426
- # the combination of the value vectors.
427
- matmul_ops = 2 * b * (num_spatial**2) * c
428
- model.total_ops += th.DoubleTensor([matmul_ops])
429
-
430
-
431
- class QKVAttentionLegacy(nn.Module):
432
- """
433
- A module which performs QKV attention. Matches legacy QKVAttention + input/output heads shaping
434
- """
435
-
436
- def __init__(self, n_heads):
437
- super().__init__()
438
- self.n_heads = n_heads
439
-
440
- def forward(self, qkv):
441
- """
442
- Apply QKV attention.
443
- :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
444
- :return: an [N x (H * C) x T] tensor after attention.
445
- """
446
- bs, width, length = qkv.shape
447
- assert width % (3 * self.n_heads) == 0
448
- ch = width // (3 * self.n_heads)
449
- q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
450
- scale = 1 / math.sqrt(math.sqrt(ch))
451
- weight = th.einsum(
452
- "bct,bcs->bts", q * scale, k * scale
453
- ) # More stable with f16 than dividing afterwards
454
- weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
455
- a = th.einsum("bts,bcs->bct", weight, v)
456
- return a.reshape(bs, -1, length)
457
-
458
- @staticmethod
459
- def count_flops(model, _x, y):
460
- return count_flops_attn(model, _x, y)
461
-
462
-
463
- class QKVAttention(nn.Module):
464
- """
465
- A module which performs QKV attention and splits in a different order.
466
- """
467
-
468
- def __init__(self, n_heads):
469
- super().__init__()
470
- self.n_heads = n_heads
471
-
472
- def forward(self, qkv):
473
- """
474
- Apply QKV attention.
475
- :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
476
- :return: an [N x (H * C) x T] tensor after attention.
477
- """
478
- bs, width, length = qkv.shape
479
- assert width % (3 * self.n_heads) == 0
480
- ch = width // (3 * self.n_heads)
481
- q, k, v = qkv.chunk(3, dim=1)
482
- scale = 1 / math.sqrt(math.sqrt(ch))
483
- weight = th.einsum(
484
- "bct,bcs->bts",
485
- (q * scale).view(bs * self.n_heads, ch, length),
486
- (k * scale).view(bs * self.n_heads, ch, length),
487
- ) # More stable with f16 than dividing afterwards
488
- weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
489
- a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
490
- return a.reshape(bs, -1, length)
491
-
492
- @staticmethod
493
- def count_flops(model, _x, y):
494
- return count_flops_attn(model, _x, y)
495
-
496
-
497
- class Timestep(nn.Module):
498
- def __init__(self, dim):
499
- super().__init__()
500
- self.dim = dim
501
-
502
- def forward(self, t):
503
- return timestep_embedding(t, self.dim)
504
-
505
-
506
- class UNetModel(nn.Module):
507
- """
508
- The full UNet model with attention and timestep embedding.
509
- :param in_channels: channels in the input Tensor.
510
- :param model_channels: base channel count for the model.
511
- :param out_channels: channels in the output Tensor.
512
- :param num_res_blocks: number of residual blocks per downsample.
513
- :param attention_resolutions: a collection of downsample rates at which
514
- attention will take place. May be a set, list, or tuple.
515
- For example, if this contains 4, then at 4x downsampling, attention
516
- will be used.
517
- :param dropout: the dropout probability.
518
- :param channel_mult: channel multiplier for each level of the UNet.
519
- :param conv_resample: if True, use learned convolutions for upsampling and
520
- downsampling.
521
- :param dims: determines if the signal is 1D, 2D, or 3D.
522
- :param num_classes: if specified (as an int), then this model will be
523
- class-conditional with `num_classes` classes.
524
- :param use_checkpoint: use gradient checkpointing to reduce memory usage.
525
- :param num_heads: the number of attention heads in each attention layer.
526
- :param num_heads_channels: if specified, ignore num_heads and instead use
527
- a fixed channel width per attention head.
528
- :param num_heads_upsample: works with num_heads to set a different number
529
- of heads for upsampling. Deprecated.
530
- :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
531
- :param resblock_updown: use residual blocks for up/downsampling.
532
- :param use_new_attention_order: use a different attention pattern for potentially
533
- increased efficiency.
534
- """
535
-
536
- def __init__(
537
- self,
538
- in_channels,
539
- model_channels,
540
- out_channels,
541
- num_res_blocks,
542
- attention_resolutions,
543
- dropout=0,
544
- channel_mult=(1, 2, 4, 8),
545
- conv_resample=True,
546
- dims=2,
547
- num_classes=None,
548
- use_checkpoint=False,
549
- use_fp16=False,
550
- num_heads=-1,
551
- num_head_channels=-1,
552
- num_heads_upsample=-1,
553
- use_scale_shift_norm=False,
554
- resblock_updown=False,
555
- use_new_attention_order=False,
556
- use_spatial_transformer=False, # custom transformer support
557
- transformer_depth=1, # custom transformer support
558
- context_dim=None, # custom transformer support
559
- n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
560
- legacy=True,
561
- disable_self_attentions=None,
562
- num_attention_blocks=None,
563
- disable_middle_self_attn=False,
564
- use_linear_in_transformer=False,
565
- spatial_transformer_attn_type="softmax",
566
- adm_in_channels=None,
567
- use_fairscale_checkpoint=False,
568
- offload_to_cpu=False,
569
- transformer_depth_middle=None,
570
- ):
571
- super().__init__()
572
- from omegaconf.listconfig import ListConfig
573
-
574
- if use_spatial_transformer:
575
- assert (
576
- context_dim is not None
577
- ), "Fool!! You forgot to include the dimension of your cross-attention conditioning..."
578
-
579
- if context_dim is not None:
580
- assert (
581
- use_spatial_transformer
582
- ), "Fool!! You forgot to use the spatial transformer for your cross-attention conditioning..."
583
- if type(context_dim) == ListConfig:
584
- context_dim = list(context_dim)
585
-
586
- if num_heads_upsample == -1:
587
- num_heads_upsample = num_heads
588
-
589
- if num_heads == -1:
590
- assert (
591
- num_head_channels != -1
592
- ), "Either num_heads or num_head_channels has to be set"
593
-
594
- if num_head_channels == -1:
595
- assert (
596
- num_heads != -1
597
- ), "Either num_heads or num_head_channels has to be set"
598
-
599
- self.in_channels = in_channels
600
- self.model_channels = model_channels
601
- self.out_channels = out_channels
602
- if isinstance(transformer_depth, int):
603
- transformer_depth = len(channel_mult) * [transformer_depth]
604
- elif isinstance(transformer_depth, ListConfig):
605
- transformer_depth = list(transformer_depth)
606
- transformer_depth_middle = default(
607
- transformer_depth_middle, transformer_depth[-1]
608
- )
609
-
610
- if isinstance(num_res_blocks, int):
611
- self.num_res_blocks = len(channel_mult) * [num_res_blocks]
612
- else:
613
- if len(num_res_blocks) != len(channel_mult):
614
- raise ValueError(
615
- "provide num_res_blocks either as an int (globally constant) or "
616
- "as a list/tuple (per-level) with the same length as channel_mult"
617
- )
618
- self.num_res_blocks = num_res_blocks
619
- # self.num_res_blocks = num_res_blocks
620
- if disable_self_attentions is not None:
621
- # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
622
- assert len(disable_self_attentions) == len(channel_mult)
623
- if num_attention_blocks is not None:
624
- assert len(num_attention_blocks) == len(self.num_res_blocks)
625
- assert all(
626
- map(
627
- lambda i: self.num_res_blocks[i] >= num_attention_blocks[i],
628
- range(len(num_attention_blocks)),
629
- )
630
- )
631
- print(
632
- f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
633
- f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
634
- f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
635
- f"attention will still not be set."
636
- ) # todo: convert to warning
637
-
638
- self.attention_resolutions = attention_resolutions
639
- self.dropout = dropout
640
- self.channel_mult = channel_mult
641
- self.conv_resample = conv_resample
642
- self.num_classes = num_classes
643
- self.use_checkpoint = use_checkpoint
644
- if use_fp16:
645
- print("WARNING: use_fp16 was dropped and has no effect anymore.")
646
- # self.dtype = th.float16 if use_fp16 else th.float32
647
- self.num_heads = num_heads
648
- self.num_head_channels = num_head_channels
649
- self.num_heads_upsample = num_heads_upsample
650
- self.predict_codebook_ids = n_embed is not None
651
-
652
- assert use_fairscale_checkpoint != use_checkpoint or not (
653
- use_checkpoint or use_fairscale_checkpoint
654
- )
655
-
656
- self.use_fairscale_checkpoint = False
657
- checkpoint_wrapper_fn = (
658
- partial(checkpoint_wrapper, offload_to_cpu=offload_to_cpu)
659
- if self.use_fairscale_checkpoint
660
- else lambda x: x
661
- )
662
-
663
- time_embed_dim = model_channels * 4
664
- self.time_embed = checkpoint_wrapper_fn(
665
- nn.Sequential(
666
- linear(model_channels, time_embed_dim),
667
- nn.SiLU(),
668
- linear(time_embed_dim, time_embed_dim),
669
- )
670
- )
671
-
672
- if self.num_classes is not None:
673
- if isinstance(self.num_classes, int):
674
- self.label_emb = nn.Embedding(num_classes, time_embed_dim)
675
- elif self.num_classes == "continuous":
676
- print("setting up linear c_adm embedding layer")
677
- self.label_emb = nn.Linear(1, time_embed_dim)
678
- elif self.num_classes == "timestep":
679
- self.label_emb = checkpoint_wrapper_fn(
680
- nn.Sequential(
681
- Timestep(model_channels),
682
- nn.Sequential(
683
- linear(model_channels, time_embed_dim),
684
- nn.SiLU(),
685
- linear(time_embed_dim, time_embed_dim),
686
- ),
687
- )
688
- )
689
- elif self.num_classes == "sequential":
690
- assert adm_in_channels is not None
691
- self.label_emb = nn.Sequential(
692
- nn.Sequential(
693
- linear(adm_in_channels, time_embed_dim),
694
- nn.SiLU(),
695
- linear(time_embed_dim, time_embed_dim),
696
- )
697
- )
698
- else:
699
- raise ValueError()
700
-
701
- self.input_blocks = nn.ModuleList(
702
- [
703
- TimestepEmbedSequential(
704
- conv_nd(dims, in_channels, model_channels, 3, padding=1)
705
- )
706
- ]
707
- )
708
- self._feature_size = model_channels
709
- input_block_chans = [model_channels]
710
- ch = model_channels
711
- ds = 1
712
- for level, mult in enumerate(channel_mult):
713
- for nr in range(self.num_res_blocks[level]):
714
- layers = [
715
- checkpoint_wrapper_fn(
716
- ResBlock(
717
- ch,
718
- time_embed_dim,
719
- dropout,
720
- out_channels=mult * model_channels,
721
- dims=dims,
722
- use_checkpoint=use_checkpoint,
723
- use_scale_shift_norm=use_scale_shift_norm,
724
- )
725
- )
726
- ]
727
- ch = mult * model_channels
728
- if ds in attention_resolutions:
729
- if num_head_channels == -1:
730
- dim_head = ch // num_heads
731
- else:
732
- num_heads = ch // num_head_channels
733
- dim_head = num_head_channels
734
- if legacy:
735
- # num_heads = 1
736
- dim_head = (
737
- ch // num_heads
738
- if use_spatial_transformer
739
- else num_head_channels
740
- )
741
- if exists(disable_self_attentions):
742
- disabled_sa = disable_self_attentions[level]
743
- else:
744
- disabled_sa = False
745
-
746
- if (
747
- not exists(num_attention_blocks)
748
- or nr < num_attention_blocks[level]
749
- ):
750
- layers.append(
751
- checkpoint_wrapper_fn(
752
- AttentionBlock(
753
- ch,
754
- use_checkpoint=use_checkpoint,
755
- num_heads=num_heads,
756
- num_head_channels=dim_head,
757
- use_new_attention_order=use_new_attention_order,
758
- )
759
- )
760
- if not use_spatial_transformer
761
- else checkpoint_wrapper_fn(
762
- SpatialTransformer(
763
- ch,
764
- num_heads,
765
- dim_head,
766
- depth=transformer_depth[level],
767
- context_dim=context_dim,
768
- disable_self_attn=disabled_sa,
769
- use_linear=use_linear_in_transformer,
770
- attn_type=spatial_transformer_attn_type,
771
- use_checkpoint=use_checkpoint,
772
- )
773
- )
774
- )
775
- self.input_blocks.append(TimestepEmbedSequential(*layers))
776
- self._feature_size += ch
777
- input_block_chans.append(ch)
778
- if level != len(channel_mult) - 1:
779
- out_ch = ch
780
- self.input_blocks.append(
781
- TimestepEmbedSequential(
782
- checkpoint_wrapper_fn(
783
- ResBlock(
784
- ch,
785
- time_embed_dim,
786
- dropout,
787
- out_channels=out_ch,
788
- dims=dims,
789
- use_checkpoint=use_checkpoint,
790
- use_scale_shift_norm=use_scale_shift_norm,
791
- down=True,
792
- )
793
- )
794
- if resblock_updown
795
- else Downsample(
796
- ch, conv_resample, dims=dims, out_channels=out_ch
797
- )
798
- )
799
- )
800
- ch = out_ch
801
- input_block_chans.append(ch)
802
- ds *= 2
803
- self._feature_size += ch
804
-
805
- if num_head_channels == -1:
806
- dim_head = ch // num_heads
807
- else:
808
- num_heads = ch // num_head_channels
809
- dim_head = num_head_channels
810
- if legacy:
811
- # num_heads = 1
812
- dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
813
- self.middle_block = TimestepEmbedSequential(
814
- checkpoint_wrapper_fn(
815
- ResBlock(
816
- ch,
817
- time_embed_dim,
818
- dropout,
819
- dims=dims,
820
- use_checkpoint=use_checkpoint,
821
- use_scale_shift_norm=use_scale_shift_norm,
822
- )
823
- ),
824
- checkpoint_wrapper_fn(
825
- AttentionBlock(
826
- ch,
827
- use_checkpoint=use_checkpoint,
828
- num_heads=num_heads,
829
- num_head_channels=dim_head,
830
- use_new_attention_order=use_new_attention_order,
831
- )
832
- )
833
- if not use_spatial_transformer
834
- else checkpoint_wrapper_fn(
835
- SpatialTransformer( # always uses a self-attn
836
- ch,
837
- num_heads,
838
- dim_head,
839
- depth=transformer_depth_middle,
840
- context_dim=context_dim,
841
- disable_self_attn=disable_middle_self_attn,
842
- use_linear=use_linear_in_transformer,
843
- attn_type=spatial_transformer_attn_type,
844
- use_checkpoint=use_checkpoint,
845
- )
846
- ),
847
- checkpoint_wrapper_fn(
848
- ResBlock(
849
- ch,
850
- time_embed_dim,
851
- dropout,
852
- dims=dims,
853
- use_checkpoint=use_checkpoint,
854
- use_scale_shift_norm=use_scale_shift_norm,
855
- )
856
- ),
857
- )
858
- self._feature_size += ch
859
-
860
- self.output_blocks = nn.ModuleList([])
861
- for level, mult in list(enumerate(channel_mult))[::-1]:
862
- for i in range(self.num_res_blocks[level] + 1):
863
- ich = input_block_chans.pop()
864
- layers = [
865
- checkpoint_wrapper_fn(
866
- ResBlock(
867
- ch + ich,
868
- time_embed_dim,
869
- dropout,
870
- out_channels=model_channels * mult,
871
- dims=dims,
872
- use_checkpoint=use_checkpoint,
873
- use_scale_shift_norm=use_scale_shift_norm,
874
- )
875
- )
876
- ]
877
- ch = model_channels * mult
878
- if ds in attention_resolutions:
879
- if num_head_channels == -1:
880
- dim_head = ch // num_heads
881
- else:
882
- num_heads = ch // num_head_channels
883
- dim_head = num_head_channels
884
- if legacy:
885
- # num_heads = 1
886
- dim_head = (
887
- ch // num_heads
888
- if use_spatial_transformer
889
- else num_head_channels
890
- )
891
- if exists(disable_self_attentions):
892
- disabled_sa = disable_self_attentions[level]
893
- else:
894
- disabled_sa = False
895
-
896
- if (
897
- not exists(num_attention_blocks)
898
- or i < num_attention_blocks[level]
899
- ):
900
- layers.append(
901
- checkpoint_wrapper_fn(
902
- AttentionBlock(
903
- ch,
904
- use_checkpoint=use_checkpoint,
905
- num_heads=num_heads_upsample,
906
- num_head_channels=dim_head,
907
- use_new_attention_order=use_new_attention_order,
908
- )
909
- )
910
- if not use_spatial_transformer
911
- else checkpoint_wrapper_fn(
912
- SpatialTransformer(
913
- ch,
914
- num_heads,
915
- dim_head,
916
- depth=transformer_depth[level],
917
- context_dim=context_dim,
918
- disable_self_attn=disabled_sa,
919
- use_linear=use_linear_in_transformer,
920
- attn_type=spatial_transformer_attn_type,
921
- use_checkpoint=use_checkpoint,
922
- )
923
- )
924
- )
925
- if level and i == self.num_res_blocks[level]:
926
- out_ch = ch
927
- layers.append(
928
- checkpoint_wrapper_fn(
929
- ResBlock(
930
- ch,
931
- time_embed_dim,
932
- dropout,
933
- out_channels=out_ch,
934
- dims=dims,
935
- use_checkpoint=use_checkpoint,
936
- use_scale_shift_norm=use_scale_shift_norm,
937
- up=True,
938
- )
939
- )
940
- if resblock_updown
941
- else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
942
- )
943
- ds //= 2
944
- self.output_blocks.append(TimestepEmbedSequential(*layers))
945
- self._feature_size += ch
946
-
947
- self.out = checkpoint_wrapper_fn(
948
- nn.Sequential(
949
- normalization(ch),
950
- nn.SiLU(),
951
- zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
952
- )
953
- )
954
- if self.predict_codebook_ids:
955
- self.id_predictor = checkpoint_wrapper_fn(
956
- nn.Sequential(
957
- normalization(ch),
958
- conv_nd(dims, model_channels, n_embed, 1),
959
- # nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
960
- )
961
- )
962
-
963
- def convert_to_fp16(self):
964
- """
965
- Convert the torso of the model to float16.
966
- """
967
- self.input_blocks.apply(convert_module_to_f16)
968
- self.middle_block.apply(convert_module_to_f16)
969
- self.output_blocks.apply(convert_module_to_f16)
970
-
971
- def convert_to_fp32(self):
972
- """
973
- Convert the torso of the model to float32.
974
- """
975
- self.input_blocks.apply(convert_module_to_f32)
976
- self.middle_block.apply(convert_module_to_f32)
977
- self.output_blocks.apply(convert_module_to_f32)
978
-
979
- def forward(self, x, timesteps=None, context=None, y=None, **kwargs):
980
- """
981
- Apply the model to an input batch.
982
- :param x: an [N x C x ...] Tensor of inputs.
983
- :param timesteps: a 1-D batch of timesteps.
984
- :param context: conditioning plugged in via crossattn
985
- :param y: an [N] Tensor of labels, if class-conditional.
986
- :return: an [N x C x ...] Tensor of outputs.
987
- """
988
- assert (y is not None) == (
989
- self.num_classes is not None
990
- ), "must specify y if and only if the model is class-conditional"
991
- hs = []
992
-
993
- t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
994
- emb = self.time_embed(t_emb)
995
-
996
- if self.num_classes is not None:
997
- assert y.shape[0] == x.shape[0]
998
- emb = emb + self.label_emb(y)
999
-
1000
- # h = x.type(self.dtype)
1001
- h = x
1002
- for module in self.input_blocks:
1003
- h = module(h, emb, context)
1004
- hs.append(h)
1005
- h = self.middle_block(h, emb, context)
1006
- for module in self.output_blocks:
1007
- h = th.cat([h, hs.pop()], dim=1)
1008
- h = module(h, emb, context)
1009
- h = h.type(x.dtype)
1010
- if self.predict_codebook_ids:
1011
- assert False, "not supported anymore. what the f*** are you doing?"
1012
- else:
1013
- return self.out(h)
1014
-
1015
-
1016
- class NoTimeUNetModel(UNetModel):
1017
- def forward(self, x, timesteps=None, context=None, y=None, **kwargs):
1018
- timesteps = th.zeros_like(timesteps)
1019
- return super().forward(x, timesteps, context, y, **kwargs)
1020
-
1021
-
1022
- class EncoderUNetModel(nn.Module):
1023
- """
1024
- The half UNet model with attention and timestep embedding.
1025
- For usage, see UNet.
1026
- """
1027
-
1028
- def __init__(
1029
- self,
1030
- image_size,
1031
- in_channels,
1032
- model_channels,
1033
- out_channels,
1034
- num_res_blocks,
1035
- attention_resolutions,
1036
- dropout=0,
1037
- channel_mult=(1, 2, 4, 8),
1038
- conv_resample=True,
1039
- dims=2,
1040
- use_checkpoint=False,
1041
- use_fp16=False,
1042
- num_heads=1,
1043
- num_head_channels=-1,
1044
- num_heads_upsample=-1,
1045
- use_scale_shift_norm=False,
1046
- resblock_updown=False,
1047
- use_new_attention_order=False,
1048
- pool="adaptive",
1049
- *args,
1050
- **kwargs,
1051
- ):
1052
- super().__init__()
1053
-
1054
- if num_heads_upsample == -1:
1055
- num_heads_upsample = num_heads
1056
-
1057
- self.in_channels = in_channels
1058
- self.model_channels = model_channels
1059
- self.out_channels = out_channels
1060
- self.num_res_blocks = num_res_blocks
1061
- self.attention_resolutions = attention_resolutions
1062
- self.dropout = dropout
1063
- self.channel_mult = channel_mult
1064
- self.conv_resample = conv_resample
1065
- self.use_checkpoint = use_checkpoint
1066
- self.dtype = th.float16 if use_fp16 else th.float32
1067
- self.num_heads = num_heads
1068
- self.num_head_channels = num_head_channels
1069
- self.num_heads_upsample = num_heads_upsample
1070
-
1071
- time_embed_dim = model_channels * 4
1072
- self.time_embed = nn.Sequential(
1073
- linear(model_channels, time_embed_dim),
1074
- nn.SiLU(),
1075
- linear(time_embed_dim, time_embed_dim),
1076
- )
1077
-
1078
- self.input_blocks = nn.ModuleList(
1079
- [
1080
- TimestepEmbedSequential(
1081
- conv_nd(dims, in_channels, model_channels, 3, padding=1)
1082
- )
1083
- ]
1084
- )
1085
- self._feature_size = model_channels
1086
- input_block_chans = [model_channels]
1087
- ch = model_channels
1088
- ds = 1
1089
- for level, mult in enumerate(channel_mult):
1090
- for _ in range(num_res_blocks):
1091
- layers = [
1092
- ResBlock(
1093
- ch,
1094
- time_embed_dim,
1095
- dropout,
1096
- out_channels=mult * model_channels,
1097
- dims=dims,
1098
- use_checkpoint=use_checkpoint,
1099
- use_scale_shift_norm=use_scale_shift_norm,
1100
- )
1101
- ]
1102
- ch = mult * model_channels
1103
- if ds in attention_resolutions:
1104
- layers.append(
1105
- AttentionBlock(
1106
- ch,
1107
- use_checkpoint=use_checkpoint,
1108
- num_heads=num_heads,
1109
- num_head_channels=num_head_channels,
1110
- use_new_attention_order=use_new_attention_order,
1111
- )
1112
- )
1113
- self.input_blocks.append(TimestepEmbedSequential(*layers))
1114
- self._feature_size += ch
1115
- input_block_chans.append(ch)
1116
- if level != len(channel_mult) - 1:
1117
- out_ch = ch
1118
- self.input_blocks.append(
1119
- TimestepEmbedSequential(
1120
- ResBlock(
1121
- ch,
1122
- time_embed_dim,
1123
- dropout,
1124
- out_channels=out_ch,
1125
- dims=dims,
1126
- use_checkpoint=use_checkpoint,
1127
- use_scale_shift_norm=use_scale_shift_norm,
1128
- down=True,
1129
- )
1130
- if resblock_updown
1131
- else Downsample(
1132
- ch, conv_resample, dims=dims, out_channels=out_ch
1133
- )
1134
- )
1135
- )
1136
- ch = out_ch
1137
- input_block_chans.append(ch)
1138
- ds *= 2
1139
- self._feature_size += ch
1140
-
1141
- self.middle_block = TimestepEmbedSequential(
1142
- ResBlock(
1143
- ch,
1144
- time_embed_dim,
1145
- dropout,
1146
- dims=dims,
1147
- use_checkpoint=use_checkpoint,
1148
- use_scale_shift_norm=use_scale_shift_norm,
1149
- ),
1150
- AttentionBlock(
1151
- ch,
1152
- use_checkpoint=use_checkpoint,
1153
- num_heads=num_heads,
1154
- num_head_channels=num_head_channels,
1155
- use_new_attention_order=use_new_attention_order,
1156
- ),
1157
- ResBlock(
1158
- ch,
1159
- time_embed_dim,
1160
- dropout,
1161
- dims=dims,
1162
- use_checkpoint=use_checkpoint,
1163
- use_scale_shift_norm=use_scale_shift_norm,
1164
- ),
1165
- )
1166
- self._feature_size += ch
1167
- self.pool = pool
1168
- if pool == "adaptive":
1169
- self.out = nn.Sequential(
1170
- normalization(ch),
1171
- nn.SiLU(),
1172
- nn.AdaptiveAvgPool2d((1, 1)),
1173
- zero_module(conv_nd(dims, ch, out_channels, 1)),
1174
- nn.Flatten(),
1175
- )
1176
- elif pool == "attention":
1177
- assert num_head_channels != -1
1178
- self.out = nn.Sequential(
1179
- normalization(ch),
1180
- nn.SiLU(),
1181
- AttentionPool2d(
1182
- (image_size // ds), ch, num_head_channels, out_channels
1183
- ),
1184
- )
1185
- elif pool == "spatial":
1186
- self.out = nn.Sequential(
1187
- nn.Linear(self._feature_size, 2048),
1188
- nn.ReLU(),
1189
- nn.Linear(2048, self.out_channels),
1190
- )
1191
- elif pool == "spatial_v2":
1192
- self.out = nn.Sequential(
1193
- nn.Linear(self._feature_size, 2048),
1194
- normalization(2048),
1195
- nn.SiLU(),
1196
- nn.Linear(2048, self.out_channels),
1197
- )
1198
- else:
1199
- raise NotImplementedError(f"Unexpected {pool} pooling")
1200
-
1201
- def convert_to_fp16(self):
1202
- """
1203
- Convert the torso of the model to float16.
1204
- """
1205
- self.input_blocks.apply(convert_module_to_f16)
1206
- self.middle_block.apply(convert_module_to_f16)
1207
-
1208
- def convert_to_fp32(self):
1209
- """
1210
- Convert the torso of the model to float32.
1211
- """
1212
- self.input_blocks.apply(convert_module_to_f32)
1213
- self.middle_block.apply(convert_module_to_f32)
1214
-
1215
- def forward(self, x, timesteps):
1216
- """
1217
- Apply the model to an input batch.
1218
- :param x: an [N x C x ...] Tensor of inputs.
1219
- :param timesteps: a 1-D batch of timesteps.
1220
- :return: an [N x K] Tensor of outputs.
1221
- """
1222
- emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
1223
-
1224
- results = []
1225
- # h = x.type(self.dtype)
1226
- h = x
1227
- for module in self.input_blocks:
1228
- h = module(h, emb)
1229
- if self.pool.startswith("spatial"):
1230
- results.append(h.type(x.dtype).mean(dim=(2, 3)))
1231
- h = self.middle_block(h, emb)
1232
- if self.pool.startswith("spatial"):
1233
- results.append(h.type(x.dtype).mean(dim=(2, 3)))
1234
- h = th.cat(results, axis=-1)
1235
- return self.out(h)
1236
- else:
1237
- h = h.type(x.dtype)
1238
- return self.out(h)
1239
-
1240
-
1241
- if __name__ == "__main__":
1242
-
1243
- class Dummy(nn.Module):
1244
- def __init__(self, in_channels=3, model_channels=64):
1245
- super().__init__()
1246
- self.input_blocks = nn.ModuleList(
1247
- [
1248
- TimestepEmbedSequential(
1249
- conv_nd(2, in_channels, model_channels, 3, padding=1)
1250
- )
1251
- ]
1252
- )
1253
-
1254
- model = UNetModel(
1255
- use_checkpoint=True,
1256
- image_size=64,
1257
- in_channels=4,
1258
- out_channels=4,
1259
- model_channels=128,
1260
- attention_resolutions=[4, 2],
1261
- num_res_blocks=2,
1262
- channel_mult=[1, 2, 4],
1263
- num_head_channels=64,
1264
- use_spatial_transformer=False,
1265
- use_linear_in_transformer=True,
1266
- transformer_depth=1,
1267
- legacy=False,
1268
- ).cuda()
1269
- x = th.randn(11, 4, 64, 64).cuda()
1270
- t = th.randint(low=0, high=10, size=(11,), device="cuda")
1271
- o = model(x, t)
1272
- print("done.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/sampling.py DELETED
@@ -1,766 +0,0 @@
1
- """
2
- Partially ported from https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/sampling.py
3
- """
4
-
5
-
6
- from typing import Dict, Union
7
-
8
- import torch
9
- from omegaconf import ListConfig, OmegaConf
10
- from tqdm import tqdm
11
-
12
- from ...modules.diffusionmodules.sampling_utils import (
13
- get_ancestral_step,
14
- linear_multistep_coeff,
15
- to_d,
16
- to_neg_log_sigma,
17
- to_sigma,
18
- )
19
- from ...util import append_dims, default, instantiate_from_config
20
- from k_diffusion.sampling import get_sigmas_karras, BrownianTreeNoiseSampler
21
-
22
- DEFAULT_GUIDER = {"target": "sgm.modules.diffusionmodules.guiders.IdentityGuider"}
23
-
24
-
25
- class BaseDiffusionSampler:
26
- def __init__(
27
- self,
28
- discretization_config: Union[Dict, ListConfig, OmegaConf],
29
- num_steps: Union[int, None] = None,
30
- guider_config: Union[Dict, ListConfig, OmegaConf, None] = None,
31
- verbose: bool = False,
32
- device: str = "cuda",
33
- ):
34
- self.num_steps = num_steps
35
- self.discretization = instantiate_from_config(discretization_config)
36
- self.guider = instantiate_from_config(
37
- default(
38
- guider_config,
39
- DEFAULT_GUIDER,
40
- )
41
- )
42
- self.verbose = verbose
43
- self.device = device
44
-
45
- def prepare_sampling_loop(self, x, cond, uc=None, num_steps=None):
46
- sigmas = self.discretization(
47
- self.num_steps if num_steps is None else num_steps, device=self.device
48
- )
49
- uc = default(uc, cond)
50
-
51
- x *= torch.sqrt(1.0 + sigmas[0] ** 2.0)
52
- num_sigmas = len(sigmas)
53
-
54
- s_in = x.new_ones([x.shape[0]])
55
-
56
- return x, s_in, sigmas, num_sigmas, cond, uc
57
-
58
- def denoise(self, x, denoiser, sigma, cond, uc):
59
- denoised = denoiser(*self.guider.prepare_inputs(x, sigma, cond, uc))
60
- denoised = self.guider(denoised, sigma)
61
- return denoised
62
-
63
- def get_sigma_gen(self, num_sigmas):
64
- sigma_generator = range(num_sigmas - 1)
65
- if self.verbose:
66
- print("#" * 30, " Sampling setting ", "#" * 30)
67
- print(f"Sampler: {self.__class__.__name__}")
68
- print(f"Discretization: {self.discretization.__class__.__name__}")
69
- print(f"Guider: {self.guider.__class__.__name__}")
70
- sigma_generator = tqdm(
71
- sigma_generator,
72
- total=num_sigmas,
73
- desc=f"Sampling with {self.__class__.__name__} for {num_sigmas} steps",
74
- )
75
- return sigma_generator
76
-
77
-
78
- class SingleStepDiffusionSampler(BaseDiffusionSampler):
79
- def sampler_step(self, sigma, next_sigma, denoiser, x, cond, uc, *args, **kwargs):
80
- raise NotImplementedError
81
-
82
- def euler_step(self, x, d, dt):
83
- return x + dt * d
84
-
85
-
86
- class EDMSampler(SingleStepDiffusionSampler):
87
- def __init__(
88
- self, s_churn=0.0, s_tmin=0.0, s_tmax=float("inf"), s_noise=1.0, *args, **kwargs
89
- ):
90
- super().__init__(*args, **kwargs)
91
-
92
- self.s_churn = s_churn
93
- self.s_tmin = s_tmin
94
- self.s_tmax = s_tmax
95
- self.s_noise = s_noise
96
-
97
- def sampler_step(self, sigma, next_sigma, denoiser, x, cond, uc=None, gamma=0.0):
98
- sigma_hat = sigma * (gamma + 1.0)
99
- if gamma > 0:
100
- eps = torch.randn_like(x) * self.s_noise
101
- x = x + eps * append_dims(sigma_hat**2 - sigma**2, x.ndim) ** 0.5
102
-
103
- denoised = self.denoise(x, denoiser, sigma_hat, cond, uc)
104
- # print('denoised', denoised.mean(axis=[0, 2, 3]))
105
- d = to_d(x, sigma_hat, denoised)
106
- dt = append_dims(next_sigma - sigma_hat, x.ndim)
107
-
108
- euler_step = self.euler_step(x, d, dt)
109
- x = self.possible_correction_step(
110
- euler_step, x, d, dt, next_sigma, denoiser, cond, uc
111
- )
112
- return x
113
-
114
- def __call__(self, denoiser, x, cond, uc=None, num_steps=None):
115
- x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop(
116
- x, cond, uc, num_steps
117
- )
118
-
119
- for i in self.get_sigma_gen(num_sigmas):
120
- gamma = (
121
- min(self.s_churn / (num_sigmas - 1), 2**0.5 - 1)
122
- if self.s_tmin <= sigmas[i] <= self.s_tmax
123
- else 0.0
124
- )
125
- x = self.sampler_step(
126
- s_in * sigmas[i],
127
- s_in * sigmas[i + 1],
128
- denoiser,
129
- x,
130
- cond,
131
- uc,
132
- gamma,
133
- )
134
-
135
- return x
136
-
137
-
138
- class AncestralSampler(SingleStepDiffusionSampler):
139
- def __init__(self, eta=1.0, s_noise=1.0, *args, **kwargs):
140
- super().__init__(*args, **kwargs)
141
-
142
- self.eta = eta
143
- self.s_noise = s_noise
144
- self.noise_sampler = lambda x: torch.randn_like(x)
145
-
146
- def ancestral_euler_step(self, x, denoised, sigma, sigma_down):
147
- d = to_d(x, sigma, denoised)
148
- dt = append_dims(sigma_down - sigma, x.ndim)
149
-
150
- return self.euler_step(x, d, dt)
151
-
152
- def ancestral_step(self, x, sigma, next_sigma, sigma_up):
153
- x = torch.where(
154
- append_dims(next_sigma, x.ndim) > 0.0,
155
- x + self.noise_sampler(x) * self.s_noise * append_dims(sigma_up, x.ndim),
156
- x,
157
- )
158
- return x
159
-
160
- def __call__(self, denoiser, x, cond, uc=None, num_steps=None):
161
- x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop(
162
- x, cond, uc, num_steps
163
- )
164
-
165
- for i in self.get_sigma_gen(num_sigmas):
166
- x = self.sampler_step(
167
- s_in * sigmas[i],
168
- s_in * sigmas[i + 1],
169
- denoiser,
170
- x,
171
- cond,
172
- uc,
173
- )
174
-
175
- return x
176
-
177
-
178
- class LinearMultistepSampler(BaseDiffusionSampler):
179
- def __init__(
180
- self,
181
- order=4,
182
- *args,
183
- **kwargs,
184
- ):
185
- super().__init__(*args, **kwargs)
186
-
187
- self.order = order
188
-
189
- def __call__(self, denoiser, x, cond, uc=None, num_steps=None, **kwargs):
190
- x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop(
191
- x, cond, uc, num_steps
192
- )
193
-
194
- ds = []
195
- sigmas_cpu = sigmas.detach().cpu().numpy()
196
- for i in self.get_sigma_gen(num_sigmas):
197
- sigma = s_in * sigmas[i]
198
- denoised = denoiser(
199
- *self.guider.prepare_inputs(x, sigma, cond, uc), **kwargs
200
- )
201
- denoised = self.guider(denoised, sigma)
202
- d = to_d(x, sigma, denoised)
203
- ds.append(d)
204
- if len(ds) > self.order:
205
- ds.pop(0)
206
- cur_order = min(i + 1, self.order)
207
- coeffs = [
208
- linear_multistep_coeff(cur_order, sigmas_cpu, i, j)
209
- for j in range(cur_order)
210
- ]
211
- x = x + sum(coeff * d for coeff, d in zip(coeffs, reversed(ds)))
212
-
213
- return x
214
-
215
-
216
- class EulerEDMSampler(EDMSampler):
217
- def possible_correction_step(
218
- self, euler_step, x, d, dt, next_sigma, denoiser, cond, uc
219
- ):
220
- # print("euler_step: ", euler_step.mean(axis=[0, 2, 3]))
221
- return euler_step
222
-
223
-
224
- class HeunEDMSampler(EDMSampler):
225
- def possible_correction_step(
226
- self, euler_step, x, d, dt, next_sigma, denoiser, cond, uc
227
- ):
228
- if torch.sum(next_sigma) < 1e-14:
229
- # Save a network evaluation if all noise levels are 0
230
- return euler_step
231
- else:
232
- denoised = self.denoise(euler_step, denoiser, next_sigma, cond, uc)
233
- d_new = to_d(euler_step, next_sigma, denoised)
234
- d_prime = (d + d_new) / 2.0
235
-
236
- # apply correction if noise level is not 0
237
- x = torch.where(
238
- append_dims(next_sigma, x.ndim) > 0.0, x + d_prime * dt, euler_step
239
- )
240
- return x
241
-
242
-
243
- class EulerAncestralSampler(AncestralSampler):
244
- def sampler_step(self, sigma, next_sigma, denoiser, x, cond, uc):
245
- sigma_down, sigma_up = get_ancestral_step(sigma, next_sigma, eta=self.eta)
246
- denoised = self.denoise(x, denoiser, sigma, cond, uc)
247
- x = self.ancestral_euler_step(x, denoised, sigma, sigma_down)
248
- x = self.ancestral_step(x, sigma, next_sigma, sigma_up)
249
-
250
- return x
251
-
252
-
253
- class DPMPP2SAncestralSampler(AncestralSampler):
254
- def get_variables(self, sigma, sigma_down):
255
- t, t_next = [to_neg_log_sigma(s) for s in (sigma, sigma_down)]
256
- h = t_next - t
257
- s = t + 0.5 * h
258
- return h, s, t, t_next
259
-
260
- def get_mult(self, h, s, t, t_next):
261
- mult1 = to_sigma(s) / to_sigma(t)
262
- mult2 = (-0.5 * h).expm1()
263
- mult3 = to_sigma(t_next) / to_sigma(t)
264
- mult4 = (-h).expm1()
265
-
266
- return mult1, mult2, mult3, mult4
267
-
268
- def sampler_step(self, sigma, next_sigma, denoiser, x, cond, uc=None, **kwargs):
269
- sigma_down, sigma_up = get_ancestral_step(sigma, next_sigma, eta=self.eta)
270
- denoised = self.denoise(x, denoiser, sigma, cond, uc)
271
- x_euler = self.ancestral_euler_step(x, denoised, sigma, sigma_down)
272
-
273
- if torch.sum(sigma_down) < 1e-14:
274
- # Save a network evaluation if all noise levels are 0
275
- x = x_euler
276
- else:
277
- h, s, t, t_next = self.get_variables(sigma, sigma_down)
278
- mult = [
279
- append_dims(mult, x.ndim) for mult in self.get_mult(h, s, t, t_next)
280
- ]
281
-
282
- x2 = mult[0] * x - mult[1] * denoised
283
- denoised2 = self.denoise(x2, denoiser, to_sigma(s), cond, uc)
284
- x_dpmpp2s = mult[2] * x - mult[3] * denoised2
285
-
286
- # apply correction if noise level is not 0
287
- x = torch.where(append_dims(sigma_down, x.ndim) > 0.0, x_dpmpp2s, x_euler)
288
-
289
- x = self.ancestral_step(x, sigma, next_sigma, sigma_up)
290
- return x
291
-
292
-
293
- class DPMPP2MSampler(BaseDiffusionSampler):
294
- def get_variables(self, sigma, next_sigma, previous_sigma=None):
295
- t, t_next = [to_neg_log_sigma(s) for s in (sigma, next_sigma)]
296
- h = t_next - t
297
-
298
- if previous_sigma is not None:
299
- h_last = t - to_neg_log_sigma(previous_sigma)
300
- r = h_last / h
301
- return h, r, t, t_next
302
- else:
303
- return h, None, t, t_next
304
-
305
- def get_mult(self, h, r, t, t_next, previous_sigma):
306
- mult1 = to_sigma(t_next) / to_sigma(t)
307
- mult2 = (-h).expm1()
308
-
309
- if previous_sigma is not None:
310
- mult3 = 1 + 1 / (2 * r)
311
- mult4 = 1 / (2 * r)
312
- return mult1, mult2, mult3, mult4
313
- else:
314
- return mult1, mult2
315
-
316
- def sampler_step(
317
- self,
318
- old_denoised,
319
- previous_sigma,
320
- sigma,
321
- next_sigma,
322
- denoiser,
323
- x,
324
- cond,
325
- uc=None,
326
- ):
327
- denoised = self.denoise(x, denoiser, sigma, cond, uc)
328
-
329
- h, r, t, t_next = self.get_variables(sigma, next_sigma, previous_sigma)
330
- mult = [
331
- append_dims(mult, x.ndim)
332
- for mult in self.get_mult(h, r, t, t_next, previous_sigma)
333
- ]
334
-
335
- x_standard = mult[0] * x - mult[1] * denoised
336
- if old_denoised is None or torch.sum(next_sigma) < 1e-14:
337
- # Save a network evaluation if all noise levels are 0 or on the first step
338
- return x_standard, denoised
339
- else:
340
- denoised_d = mult[2] * denoised - mult[3] * old_denoised
341
- x_advanced = mult[0] * x - mult[1] * denoised_d
342
-
343
- # apply correction if noise level is not 0 and not first step
344
- x = torch.where(
345
- append_dims(next_sigma, x.ndim) > 0.0, x_advanced, x_standard
346
- )
347
-
348
- return x, denoised
349
-
350
- def __call__(self, denoiser, x, cond, uc=None, num_steps=None, **kwargs):
351
- x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop(
352
- x, cond, uc, num_steps
353
- )
354
-
355
- old_denoised = None
356
- for i in self.get_sigma_gen(num_sigmas):
357
- x, old_denoised = self.sampler_step(
358
- old_denoised,
359
- None if i == 0 else s_in * sigmas[i - 1],
360
- s_in * sigmas[i],
361
- s_in * sigmas[i + 1],
362
- denoiser,
363
- x,
364
- cond,
365
- uc=uc,
366
- )
367
-
368
- return x
369
-
370
-
371
- class SubstepSampler(EulerAncestralSampler):
372
- def __init__(self, s_churn=0.0, s_tmin=0.0, s_tmax=float("inf"), s_noise=1.0, restore_cfg=4.0,
373
- restore_cfg_s_tmin=0.05, eta=1., n_sample_steps=4, *args, **kwargs):
374
- super().__init__(*args, **kwargs)
375
- self.n_sample_steps = n_sample_steps
376
- self.steps_subset = [0, 100, 200, 300, 1000]
377
-
378
- def prepare_sampling_loop(self, x, cond, uc=None, num_steps=None):
379
- sigmas = self.discretization(1000, device=self.device)
380
- sigmas = sigmas[
381
- self.steps_subset[: self.num_steps] + self.steps_subset[-1:]
382
- ]
383
- print(sigmas)
384
- # uc = cond
385
- x *= torch.sqrt(1.0 + sigmas[0] ** 2.0)
386
- num_sigmas = len(sigmas)
387
- s_in = x.new_ones([x.shape[0]])
388
- return x, s_in, sigmas, num_sigmas, cond, uc
389
-
390
- def denoise(self, x, denoiser, sigma, cond, uc, control_scale=1.0):
391
- denoised = denoiser(*self.guider.prepare_inputs(x, sigma, cond, uc), control_scale)
392
- denoised = self.guider(denoised, sigma)
393
- return denoised
394
-
395
- def __call__(self, denoiser, x, cond, uc=None, num_steps=None, control_scale=1.0, *args, **kwargs):
396
- x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop(
397
- x, cond, uc, num_steps
398
- )
399
-
400
- for i in self.get_sigma_gen(num_sigmas):
401
- x = self.sampler_step(
402
- s_in * sigmas[i],
403
- s_in * sigmas[i + 1],
404
- denoiser,
405
- x,
406
- cond,
407
- uc,
408
- control_scale=control_scale,
409
- )
410
-
411
- return x
412
-
413
- def sampler_step(self, sigma, next_sigma, denoiser, x, cond, uc, control_scale=1.0):
414
- sigma_down, sigma_up = get_ancestral_step(sigma, next_sigma, eta=self.eta)
415
- denoised = self.denoise(x, denoiser, sigma, cond, uc, control_scale=control_scale)
416
- x = self.ancestral_euler_step(x, denoised, sigma, sigma_down)
417
- x = self.ancestral_step(x, sigma, next_sigma, sigma_up)
418
-
419
- return x
420
-
421
-
422
- class RestoreDPMPP2MSampler(DPMPP2MSampler):
423
- def __init__(self, s_churn=0.0, s_tmin=0.0, s_tmax=float("inf"), s_noise=1.0, restore_cfg=4.0,
424
- restore_cfg_s_tmin=0.05, eta=1., *args, **kwargs):
425
- self.s_noise = s_noise
426
- self.eta = eta
427
- super().__init__(*args, **kwargs)
428
-
429
- def denoise(self, x, denoiser, sigma, cond, uc, control_scale=1.0):
430
- denoised = denoiser(*self.guider.prepare_inputs(x, sigma, cond, uc), control_scale)
431
- denoised = self.guider(denoised, sigma)
432
- return denoised
433
-
434
- def get_mult(self, h, r, t, t_next, previous_sigma):
435
- eta_h = self.eta * h
436
- mult1 = to_sigma(t_next) / to_sigma(t) * (-eta_h).exp()
437
- mult2 = (-h -eta_h).expm1()
438
-
439
- if previous_sigma is not None:
440
- mult3 = 1 + 1 / (2 * r)
441
- mult4 = 1 / (2 * r)
442
- return mult1, mult2, mult3, mult4
443
- else:
444
- return mult1, mult2
445
-
446
-
447
- def sampler_step(
448
- self,
449
- old_denoised,
450
- previous_sigma,
451
- sigma,
452
- next_sigma,
453
- denoiser,
454
- x,
455
- cond,
456
- uc=None,
457
- eps_noise=None,
458
- control_scale=1.0,
459
- ):
460
- denoised = self.denoise(x, denoiser, sigma, cond, uc, control_scale=control_scale)
461
-
462
- h, r, t, t_next = self.get_variables(sigma, next_sigma, previous_sigma)
463
- eta_h = self.eta * h
464
- mult = [
465
- append_dims(mult, x.ndim)
466
- for mult in self.get_mult(h, r, t, t_next, previous_sigma)
467
- ]
468
-
469
- x_standard = mult[0] * x - mult[1] * denoised
470
- if old_denoised is None or torch.sum(next_sigma) < 1e-14:
471
- # Save a network evaluation if all noise levels are 0 or on the first step
472
- return x_standard, denoised
473
- else:
474
- denoised_d = mult[2] * denoised - mult[3] * old_denoised
475
- x_advanced = mult[0] * x - mult[1] * denoised_d
476
-
477
- # apply correction if noise level is not 0 and not first step
478
- x = torch.where(
479
- append_dims(next_sigma, x.ndim) > 0.0, x_advanced, x_standard
480
- )
481
- if self.eta:
482
- x = x + eps_noise * next_sigma * (-2 * eta_h).expm1().neg().sqrt() * self.s_noise
483
-
484
- return x, denoised
485
-
486
- def __call__(self, denoiser, x, cond, uc=None, num_steps=None, control_scale=1.0, **kwargs):
487
- x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop(
488
- x, cond, uc, num_steps
489
- )
490
- sigmas_min, sigmas_max = sigmas[-2].cpu(), sigmas[0].cpu()
491
- sigmas_new = get_sigmas_karras(self.num_steps, sigmas_min, sigmas_max, device=x.device)
492
- sigmas = sigmas_new
493
-
494
- noise_sampler = BrownianTreeNoiseSampler(x, sigmas_min, sigmas_max)
495
-
496
- old_denoised = None
497
- for i in self.get_sigma_gen(num_sigmas):
498
- if i > 0 and torch.sum(s_in * sigmas[i + 1]) > 1e-14:
499
- eps_noise = noise_sampler(s_in * sigmas[i], s_in * sigmas[i + 1])
500
- else:
501
- eps_noise = None
502
- x, old_denoised = self.sampler_step(
503
- old_denoised,
504
- None if i == 0 else s_in * sigmas[i - 1],
505
- s_in * sigmas[i],
506
- s_in * sigmas[i + 1],
507
- denoiser,
508
- x,
509
- cond,
510
- uc=uc,
511
- eps_noise=eps_noise,
512
- control_scale=control_scale,
513
- )
514
-
515
- return x
516
-
517
-
518
- def to_d_center(denoised, x_center, x):
519
- b = denoised.shape[0]
520
- v_center = (denoised - x_center).view(b, -1)
521
- v_denoise = (x - denoised).view(b, -1)
522
- d_center = v_center - v_denoise * (v_center * v_denoise).sum(dim=1).view(b, 1) / \
523
- (v_denoise * v_denoise).sum(dim=1).view(b, 1)
524
- d_center = d_center / d_center.view(x.shape[0], -1).norm(dim=1).view(-1, 1)
525
- return d_center.view(denoised.shape)
526
-
527
-
528
- class RestoreEDMSampler(SingleStepDiffusionSampler):
529
- def __init__(
530
- self, s_churn=0.0, s_tmin=0.0, s_tmax=float("inf"), s_noise=1.0, restore_cfg=4.0,
531
- restore_cfg_s_tmin=0.05, *args, **kwargs
532
- ):
533
- super().__init__(*args, **kwargs)
534
-
535
- self.s_churn = s_churn
536
- self.s_tmin = s_tmin
537
- self.s_tmax = s_tmax
538
- self.s_noise = s_noise
539
- self.restore_cfg = restore_cfg
540
- self.restore_cfg_s_tmin = restore_cfg_s_tmin
541
- self.sigma_max = 14.6146
542
-
543
- def denoise(self, x, denoiser, sigma, cond, uc, control_scale=1.0):
544
- denoised = denoiser(*self.guider.prepare_inputs(x, sigma, cond, uc), control_scale)
545
- denoised = self.guider(denoised, sigma)
546
- return denoised
547
-
548
- def sampler_step(self, sigma, next_sigma, denoiser, x, cond, uc=None, gamma=0.0, x_center=None, eps_noise=None,
549
- control_scale=1.0, use_linear_control_scale=False, control_scale_start=0.0):
550
- sigma_hat = sigma * (gamma + 1.0)
551
- if gamma > 0:
552
- if eps_noise is not None:
553
- eps = eps_noise * self.s_noise
554
- else:
555
- eps = torch.randn_like(x) * self.s_noise
556
- x = x + eps * append_dims(sigma_hat**2 - sigma**2, x.ndim) ** 0.5
557
-
558
- if use_linear_control_scale:
559
- control_scale = (sigma[0].item() / self.sigma_max) * (control_scale_start - control_scale) + control_scale
560
-
561
- denoised = self.denoise(x, denoiser, sigma_hat, cond, uc, control_scale=control_scale)
562
-
563
- if (next_sigma[0] > self.restore_cfg_s_tmin) and (self.restore_cfg > 0):
564
- d_center = (denoised - x_center)
565
- denoised = denoised - d_center * ((sigma.view(-1, 1, 1, 1) / self.sigma_max) ** self.restore_cfg)
566
-
567
- d = to_d(x, sigma_hat, denoised)
568
- dt = append_dims(next_sigma - sigma_hat, x.ndim)
569
- x = self.euler_step(x, d, dt)
570
- return x
571
-
572
- def __call__(self, denoiser, x, cond, uc=None, num_steps=None, x_center=None, control_scale=1.0,
573
- use_linear_control_scale=False, control_scale_start=0.0):
574
- x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop(
575
- x, cond, uc, num_steps
576
- )
577
-
578
- for _idx, i in enumerate(self.get_sigma_gen(num_sigmas)):
579
- gamma = (
580
- min(self.s_churn / (num_sigmas - 1), 2**0.5 - 1)
581
- if self.s_tmin <= sigmas[i] <= self.s_tmax
582
- else 0.0
583
- )
584
- x = self.sampler_step(
585
- s_in * sigmas[i],
586
- s_in * sigmas[i + 1],
587
- denoiser,
588
- x,
589
- cond,
590
- uc,
591
- gamma,
592
- x_center,
593
- control_scale=control_scale,
594
- use_linear_control_scale=use_linear_control_scale,
595
- control_scale_start=control_scale_start,
596
- )
597
- return x
598
-
599
-
600
- class TiledRestoreEDMSampler(RestoreEDMSampler):
601
- def __init__(self, tile_size=128, tile_stride=64, *args, **kwargs):
602
- super().__init__(*args, **kwargs)
603
- self.tile_size = tile_size
604
- self.tile_stride = tile_stride
605
- self.tile_weights = gaussian_weights(self.tile_size, self.tile_size, 1)
606
-
607
- def __call__(self, denoiser, x, cond, uc=None, num_steps=None, x_center=None, control_scale=1.0,
608
- use_linear_control_scale=False, control_scale_start=0.0):
609
- use_local_prompt = isinstance(cond, list)
610
- b, _, h, w = x.shape
611
- latent_tiles_iterator = _sliding_windows(h, w, self.tile_size, self.tile_stride)
612
- tile_weights = self.tile_weights.repeat(b, 1, 1, 1)
613
- if not use_local_prompt:
614
- LQ_latent = cond['control']
615
- else:
616
- assert len(cond) == len(latent_tiles_iterator), "Number of local prompts should be equal to number of tiles"
617
- LQ_latent = cond[0]['control']
618
- clean_LQ_latent = x_center
619
- x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop(
620
- x, cond, uc, num_steps
621
- )
622
-
623
- for _idx, i in enumerate(self.get_sigma_gen(num_sigmas)):
624
- gamma = (
625
- min(self.s_churn / (num_sigmas - 1), 2**0.5 - 1)
626
- if self.s_tmin <= sigmas[i] <= self.s_tmax
627
- else 0.0
628
- )
629
- x_next = torch.zeros_like(x)
630
- count = torch.zeros_like(x)
631
- eps_noise = torch.randn_like(x)
632
- for j, (hi, hi_end, wi, wi_end) in enumerate(latent_tiles_iterator):
633
- x_tile = x[:, :, hi:hi_end, wi:wi_end]
634
- _eps_noise = eps_noise[:, :, hi:hi_end, wi:wi_end]
635
- x_center_tile = clean_LQ_latent[:, :, hi:hi_end, wi:wi_end]
636
- if use_local_prompt:
637
- _cond = cond[j]
638
- else:
639
- _cond = cond
640
- _cond['control'] = LQ_latent[:, :, hi:hi_end, wi:wi_end]
641
- uc['control'] = LQ_latent[:, :, hi:hi_end, wi:wi_end]
642
- _x = self.sampler_step(
643
- s_in * sigmas[i],
644
- s_in * sigmas[i + 1],
645
- denoiser,
646
- x_tile,
647
- _cond,
648
- uc,
649
- gamma,
650
- x_center_tile,
651
- eps_noise=_eps_noise,
652
- control_scale=control_scale,
653
- use_linear_control_scale=use_linear_control_scale,
654
- control_scale_start=control_scale_start,
655
- )
656
- x_next[:, :, hi:hi_end, wi:wi_end] += _x * tile_weights
657
- count[:, :, hi:hi_end, wi:wi_end] += tile_weights
658
- x_next /= count
659
- x = x_next
660
- return x
661
-
662
-
663
- class TiledRestoreDPMPP2MSampler(RestoreDPMPP2MSampler):
664
- def __init__(self, tile_size=128, tile_stride=64, *args, **kwargs):
665
- super().__init__(*args, **kwargs)
666
- self.tile_size = tile_size
667
- self.tile_stride = tile_stride
668
- self.tile_weights = gaussian_weights(self.tile_size, self.tile_size, 1)
669
-
670
- def __call__(self, denoiser, x, cond, uc=None, num_steps=None, control_scale=1.0, **kwargs):
671
- use_local_prompt = isinstance(cond, list)
672
- b, _, h, w = x.shape
673
- latent_tiles_iterator = _sliding_windows(h, w, self.tile_size, self.tile_stride)
674
- tile_weights = self.tile_weights.repeat(b, 1, 1, 1)
675
- if not use_local_prompt:
676
- LQ_latent = cond['control']
677
- else:
678
- assert len(cond) == len(latent_tiles_iterator), "Number of local prompts should be equal to number of tiles"
679
- LQ_latent = cond[0]['control']
680
- x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop(
681
- x, cond, uc, num_steps
682
- )
683
- sigmas_min, sigmas_max = sigmas[-2].cpu(), sigmas[0].cpu()
684
- sigmas_new = get_sigmas_karras(self.num_steps, sigmas_min, sigmas_max, device=x.device)
685
- sigmas = sigmas_new
686
-
687
- noise_sampler = BrownianTreeNoiseSampler(x, sigmas_min, sigmas_max)
688
-
689
- old_denoised = None
690
- for _idx, i in enumerate(self.get_sigma_gen(num_sigmas)):
691
- if i > 0 and torch.sum(s_in * sigmas[i + 1]) > 1e-14:
692
- eps_noise = noise_sampler(s_in * sigmas[i], s_in * sigmas[i + 1])
693
- else:
694
- eps_noise = torch.zeros_like(x)
695
- x_next = torch.zeros_like(x)
696
- old_denoised_next = torch.zeros_like(x)
697
- count = torch.zeros_like(x)
698
- for j, (hi, hi_end, wi, wi_end) in enumerate(latent_tiles_iterator):
699
- x_tile = x[:, :, hi:hi_end, wi:wi_end]
700
- _eps_noise = eps_noise[:, :, hi:hi_end, wi:wi_end]
701
- if old_denoised is not None:
702
- old_denoised_tile = old_denoised[:, :, hi:hi_end, wi:wi_end]
703
- else:
704
- old_denoised_tile = None
705
- if use_local_prompt:
706
- _cond = cond[j]
707
- else:
708
- _cond = cond
709
- _cond['control'] = LQ_latent[:, :, hi:hi_end, wi:wi_end]
710
- uc['control'] = LQ_latent[:, :, hi:hi_end, wi:wi_end]
711
- _x, _old_denoised = self.sampler_step(
712
- old_denoised_tile,
713
- None if i == 0 else s_in * sigmas[i - 1],
714
- s_in * sigmas[i],
715
- s_in * sigmas[i + 1],
716
- denoiser,
717
- x_tile,
718
- _cond,
719
- uc=uc,
720
- eps_noise=_eps_noise,
721
- control_scale=control_scale,
722
- )
723
- x_next[:, :, hi:hi_end, wi:wi_end] += _x * tile_weights
724
- old_denoised_next[:, :, hi:hi_end, wi:wi_end] += _old_denoised * tile_weights
725
- count[:, :, hi:hi_end, wi:wi_end] += tile_weights
726
- old_denoised_next /= count
727
- x_next /= count
728
- x = x_next
729
- old_denoised = old_denoised_next
730
- return x
731
-
732
-
733
- def gaussian_weights(tile_width, tile_height, nbatches):
734
- """Generates a gaussian mask of weights for tile contributions"""
735
- from numpy import pi, exp, sqrt
736
- import numpy as np
737
-
738
- latent_width = tile_width
739
- latent_height = tile_height
740
-
741
- var = 0.01
742
- midpoint = (latent_width - 1) / 2 # -1 because index goes from 0 to latent_width - 1
743
- x_probs = [exp(-(x - midpoint) * (x - midpoint) / (latent_width * latent_width) / (2 * var)) / sqrt(2 * pi * var)
744
- for x in range(latent_width)]
745
- midpoint = latent_height / 2
746
- y_probs = [exp(-(y - midpoint) * (y - midpoint) / (latent_height * latent_height) / (2 * var)) / sqrt(2 * pi * var)
747
- for y in range(latent_height)]
748
-
749
- weights = np.outer(y_probs, x_probs)
750
- return torch.tile(torch.tensor(weights, device='cuda'), (nbatches, 4, 1, 1))
751
-
752
-
753
- def _sliding_windows(h: int, w: int, tile_size: int, tile_stride: int):
754
- hi_list = list(range(0, h - tile_size + 1, tile_stride))
755
- if (h - tile_size) % tile_stride != 0:
756
- hi_list.append(h - tile_size)
757
-
758
- wi_list = list(range(0, w - tile_size + 1, tile_stride))
759
- if (w - tile_size) % tile_stride != 0:
760
- wi_list.append(w - tile_size)
761
-
762
- coords = []
763
- for hi in hi_list:
764
- for wi in wi_list:
765
- coords.append((hi, hi + tile_size, wi, wi + tile_size))
766
- return coords
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/sampling_utils.py DELETED
@@ -1,48 +0,0 @@
1
- import torch
2
- from scipy import integrate
3
-
4
- from ...util import append_dims
5
-
6
-
7
- class NoDynamicThresholding:
8
- def __call__(self, uncond, cond, scale):
9
- return uncond + scale.view(-1, 1, 1, 1) * (cond - uncond)
10
-
11
-
12
- def linear_multistep_coeff(order, t, i, j, epsrel=1e-4):
13
- if order - 1 > i:
14
- raise ValueError(f"Order {order} too high for step {i}")
15
-
16
- def fn(tau):
17
- prod = 1.0
18
- for k in range(order):
19
- if j == k:
20
- continue
21
- prod *= (tau - t[i - k]) / (t[i - j] - t[i - k])
22
- return prod
23
-
24
- return integrate.quad(fn, t[i], t[i + 1], epsrel=epsrel)[0]
25
-
26
-
27
- def get_ancestral_step(sigma_from, sigma_to, eta=1.0):
28
- if not eta:
29
- return sigma_to, 0.0
30
- sigma_up = torch.minimum(
31
- sigma_to,
32
- eta
33
- * (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5,
34
- )
35
- sigma_down = (sigma_to**2 - sigma_up**2) ** 0.5
36
- return sigma_down, sigma_up
37
-
38
-
39
- def to_d(x, sigma, denoised):
40
- return (x - denoised) / append_dims(sigma, x.ndim)
41
-
42
-
43
- def to_neg_log_sigma(sigma):
44
- return sigma.log().neg()
45
-
46
-
47
- def to_sigma(neg_log_sigma):
48
- return neg_log_sigma.neg().exp()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/sigma_sampling.py DELETED
@@ -1,40 +0,0 @@
1
- import torch
2
-
3
- from ...util import default, instantiate_from_config
4
-
5
-
6
- class EDMSampling:
7
- def __init__(self, p_mean=-1.2, p_std=1.2):
8
- self.p_mean = p_mean
9
- self.p_std = p_std
10
-
11
- def __call__(self, n_samples, rand=None):
12
- log_sigma = self.p_mean + self.p_std * default(rand, torch.randn((n_samples,)))
13
- return log_sigma.exp()
14
-
15
-
16
- class DiscreteSampling:
17
- def __init__(self, discretization_config, num_idx, do_append_zero=False, flip=True, idx_range=None):
18
- self.num_idx = num_idx
19
- self.sigmas = instantiate_from_config(discretization_config)(
20
- num_idx, do_append_zero=do_append_zero, flip=flip
21
- )
22
- self.idx_range = idx_range
23
-
24
- def idx_to_sigma(self, idx):
25
- # print(self.sigmas[idx])
26
- return self.sigmas[idx]
27
-
28
- def __call__(self, n_samples, rand=None):
29
- if self.idx_range is None:
30
- idx = default(
31
- rand,
32
- torch.randint(0, self.num_idx, (n_samples,)),
33
- )
34
- else:
35
- idx = default(
36
- rand,
37
- torch.randint(self.idx_range[0], self.idx_range[1], (n_samples,)),
38
- )
39
- return self.idx_to_sigma(idx)
40
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/util.py DELETED
@@ -1,309 +0,0 @@
1
- """
2
- adopted from
3
- https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
4
- and
5
- https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
6
- and
7
- https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
8
-
9
- thanks!
10
- """
11
-
12
- import math
13
-
14
- import torch
15
- import torch.nn as nn
16
- from einops import repeat
17
-
18
-
19
- def make_beta_schedule(
20
- schedule,
21
- n_timestep,
22
- linear_start=1e-4,
23
- linear_end=2e-2,
24
- ):
25
- if schedule == "linear":
26
- betas = (
27
- torch.linspace(
28
- linear_start**0.5, linear_end**0.5, n_timestep, dtype=torch.float64
29
- )
30
- ** 2
31
- )
32
- return betas.numpy()
33
-
34
-
35
- def extract_into_tensor(a, t, x_shape):
36
- b, *_ = t.shape
37
- out = a.gather(-1, t)
38
- return out.reshape(b, *((1,) * (len(x_shape) - 1)))
39
-
40
-
41
- def mixed_checkpoint(func, inputs: dict, params, flag):
42
- """
43
- Evaluate a function without caching intermediate activations, allowing for
44
- reduced memory at the expense of extra compute in the backward pass. This differs from the original checkpoint function
45
- borrowed from https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py in that
46
- it also works with non-tensor inputs
47
- :param func: the function to evaluate.
48
- :param inputs: the argument dictionary to pass to `func`.
49
- :param params: a sequence of parameters `func` depends on but does not
50
- explicitly take as arguments.
51
- :param flag: if False, disable gradient checkpointing.
52
- """
53
- if flag:
54
- tensor_keys = [key for key in inputs if isinstance(inputs[key], torch.Tensor)]
55
- tensor_inputs = [
56
- inputs[key] for key in inputs if isinstance(inputs[key], torch.Tensor)
57
- ]
58
- non_tensor_keys = [
59
- key for key in inputs if not isinstance(inputs[key], torch.Tensor)
60
- ]
61
- non_tensor_inputs = [
62
- inputs[key] for key in inputs if not isinstance(inputs[key], torch.Tensor)
63
- ]
64
- args = tuple(tensor_inputs) + tuple(non_tensor_inputs) + tuple(params)
65
- return MixedCheckpointFunction.apply(
66
- func,
67
- len(tensor_inputs),
68
- len(non_tensor_inputs),
69
- tensor_keys,
70
- non_tensor_keys,
71
- *args,
72
- )
73
- else:
74
- return func(**inputs)
75
-
76
-
77
- class MixedCheckpointFunction(torch.autograd.Function):
78
- @staticmethod
79
- def forward(
80
- ctx,
81
- run_function,
82
- length_tensors,
83
- length_non_tensors,
84
- tensor_keys,
85
- non_tensor_keys,
86
- *args,
87
- ):
88
- ctx.end_tensors = length_tensors
89
- ctx.end_non_tensors = length_tensors + length_non_tensors
90
- ctx.gpu_autocast_kwargs = {
91
- "enabled": torch.is_autocast_enabled(),
92
- "dtype": torch.get_autocast_gpu_dtype(),
93
- "cache_enabled": torch.is_autocast_cache_enabled(),
94
- }
95
- assert (
96
- len(tensor_keys) == length_tensors
97
- and len(non_tensor_keys) == length_non_tensors
98
- )
99
-
100
- ctx.input_tensors = {
101
- key: val for (key, val) in zip(tensor_keys, list(args[: ctx.end_tensors]))
102
- }
103
- ctx.input_non_tensors = {
104
- key: val
105
- for (key, val) in zip(
106
- non_tensor_keys, list(args[ctx.end_tensors : ctx.end_non_tensors])
107
- )
108
- }
109
- ctx.run_function = run_function
110
- ctx.input_params = list(args[ctx.end_non_tensors :])
111
-
112
- with torch.no_grad():
113
- output_tensors = ctx.run_function(
114
- **ctx.input_tensors, **ctx.input_non_tensors
115
- )
116
- return output_tensors
117
-
118
- @staticmethod
119
- def backward(ctx, *output_grads):
120
- # additional_args = {key: ctx.input_tensors[key] for key in ctx.input_tensors if not isinstance(ctx.input_tensors[key],torch.Tensor)}
121
- ctx.input_tensors = {
122
- key: ctx.input_tensors[key].detach().requires_grad_(True)
123
- for key in ctx.input_tensors
124
- }
125
-
126
- with torch.enable_grad(), torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
127
- # Fixes a bug where the first op in run_function modifies the
128
- # Tensor storage in place, which is not allowed for detach()'d
129
- # Tensors.
130
- shallow_copies = {
131
- key: ctx.input_tensors[key].view_as(ctx.input_tensors[key])
132
- for key in ctx.input_tensors
133
- }
134
- # shallow_copies.update(additional_args)
135
- output_tensors = ctx.run_function(**shallow_copies, **ctx.input_non_tensors)
136
- input_grads = torch.autograd.grad(
137
- output_tensors,
138
- list(ctx.input_tensors.values()) + ctx.input_params,
139
- output_grads,
140
- allow_unused=True,
141
- )
142
- del ctx.input_tensors
143
- del ctx.input_params
144
- del output_tensors
145
- return (
146
- (None, None, None, None, None)
147
- + input_grads[: ctx.end_tensors]
148
- + (None,) * (ctx.end_non_tensors - ctx.end_tensors)
149
- + input_grads[ctx.end_tensors :]
150
- )
151
-
152
-
153
- def checkpoint(func, inputs, params, flag):
154
- """
155
- Evaluate a function without caching intermediate activations, allowing for
156
- reduced memory at the expense of extra compute in the backward pass.
157
- :param func: the function to evaluate.
158
- :param inputs: the argument sequence to pass to `func`.
159
- :param params: a sequence of parameters `func` depends on but does not
160
- explicitly take as arguments.
161
- :param flag: if False, disable gradient checkpointing.
162
- """
163
- if flag:
164
- args = tuple(inputs) + tuple(params)
165
- return CheckpointFunction.apply(func, len(inputs), *args)
166
- else:
167
- return func(*inputs)
168
-
169
-
170
- class CheckpointFunction(torch.autograd.Function):
171
- @staticmethod
172
- def forward(ctx, run_function, length, *args):
173
- ctx.run_function = run_function
174
- ctx.input_tensors = list(args[:length])
175
- ctx.input_params = list(args[length:])
176
- ctx.gpu_autocast_kwargs = {
177
- "enabled": torch.is_autocast_enabled(),
178
- "dtype": torch.get_autocast_gpu_dtype(),
179
- "cache_enabled": torch.is_autocast_cache_enabled(),
180
- }
181
- with torch.no_grad():
182
- output_tensors = ctx.run_function(*ctx.input_tensors)
183
- return output_tensors
184
-
185
- @staticmethod
186
- def backward(ctx, *output_grads):
187
- ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
188
- with torch.enable_grad(), torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
189
- # Fixes a bug where the first op in run_function modifies the
190
- # Tensor storage in place, which is not allowed for detach()'d
191
- # Tensors.
192
- shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
193
- output_tensors = ctx.run_function(*shallow_copies)
194
- input_grads = torch.autograd.grad(
195
- output_tensors,
196
- ctx.input_tensors + ctx.input_params,
197
- output_grads,
198
- allow_unused=True,
199
- )
200
- del ctx.input_tensors
201
- del ctx.input_params
202
- del output_tensors
203
- return (None, None) + input_grads
204
-
205
-
206
- def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
207
- """
208
- Create sinusoidal timestep embeddings.
209
- :param timesteps: a 1-D Tensor of N indices, one per batch element.
210
- These may be fractional.
211
- :param dim: the dimension of the output.
212
- :param max_period: controls the minimum frequency of the embeddings.
213
- :return: an [N x dim] Tensor of positional embeddings.
214
- """
215
- if not repeat_only:
216
- half = dim // 2
217
- freqs = torch.exp(
218
- -math.log(max_period)
219
- * torch.arange(start=0, end=half, dtype=torch.float32)
220
- / half
221
- ).to(device=timesteps.device)
222
- args = timesteps[:, None].float() * freqs[None]
223
- embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
224
- if dim % 2:
225
- embedding = torch.cat(
226
- [embedding, torch.zeros_like(embedding[:, :1])], dim=-1
227
- )
228
- else:
229
- embedding = repeat(timesteps, "b -> b d", d=dim)
230
- return embedding
231
-
232
-
233
- def zero_module(module):
234
- """
235
- Zero out the parameters of a module and return it.
236
- """
237
- for p in module.parameters():
238
- p.detach().zero_()
239
- return module
240
-
241
-
242
- def scale_module(module, scale):
243
- """
244
- Scale the parameters of a module and return it.
245
- """
246
- for p in module.parameters():
247
- p.detach().mul_(scale)
248
- return module
249
-
250
-
251
- def mean_flat(tensor):
252
- """
253
- Take the mean over all non-batch dimensions.
254
- """
255
- return tensor.mean(dim=list(range(1, len(tensor.shape))))
256
-
257
-
258
- def normalization(channels):
259
- """
260
- Make a standard normalization layer.
261
- :param channels: number of input channels.
262
- :return: an nn.Module for normalization.
263
- """
264
- return GroupNorm32(32, channels)
265
-
266
-
267
- # PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
268
- class SiLU(nn.Module):
269
- def forward(self, x):
270
- return x * torch.sigmoid(x)
271
-
272
-
273
- class GroupNorm32(nn.GroupNorm):
274
- def forward(self, x):
275
- # return super().forward(x.float()).type(x.dtype)
276
- return super().forward(x)
277
-
278
-
279
- def conv_nd(dims, *args, **kwargs):
280
- """
281
- Create a 1D, 2D, or 3D convolution module.
282
- """
283
- if dims == 1:
284
- return nn.Conv1d(*args, **kwargs)
285
- elif dims == 2:
286
- return nn.Conv2d(*args, **kwargs)
287
- elif dims == 3:
288
- return nn.Conv3d(*args, **kwargs)
289
- raise ValueError(f"unsupported dimensions: {dims}")
290
-
291
-
292
- def linear(*args, **kwargs):
293
- """
294
- Create a linear module.
295
- """
296
- return nn.Linear(*args, **kwargs)
297
-
298
-
299
- def avg_pool_nd(dims, *args, **kwargs):
300
- """
301
- Create a 1D, 2D, or 3D average pooling module.
302
- """
303
- if dims == 1:
304
- return nn.AvgPool1d(*args, **kwargs)
305
- elif dims == 2:
306
- return nn.AvgPool2d(*args, **kwargs)
307
- elif dims == 3:
308
- return nn.AvgPool3d(*args, **kwargs)
309
- raise ValueError(f"unsupported dimensions: {dims}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/diffusionmodules/wrappers.py DELETED
@@ -1,103 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- from packaging import version
4
- # import torch._dynamo
5
- # torch._dynamo.config.suppress_errors = True
6
- # torch._dynamo.config.cache_size_limit = 512
7
-
8
- OPENAIUNETWRAPPER = "sgm.modules.diffusionmodules.wrappers.OpenAIWrapper"
9
-
10
-
11
- class IdentityWrapper(nn.Module):
12
- def __init__(self, diffusion_model, compile_model: bool = False):
13
- super().__init__()
14
- compile = (
15
- torch.compile
16
- if (version.parse(torch.__version__) >= version.parse("2.0.0"))
17
- and compile_model
18
- else lambda x: x
19
- )
20
- self.diffusion_model = compile(diffusion_model)
21
-
22
- def forward(self, *args, **kwargs):
23
- return self.diffusion_model(*args, **kwargs)
24
-
25
-
26
- class OpenAIWrapper(IdentityWrapper):
27
- def forward(
28
- self, x: torch.Tensor, t: torch.Tensor, c: dict, **kwargs
29
- ) -> torch.Tensor:
30
- x = torch.cat((x, c.get("concat", torch.Tensor([]).type_as(x))), dim=1)
31
- return self.diffusion_model(
32
- x,
33
- timesteps=t,
34
- context=c.get("crossattn", None),
35
- y=c.get("vector", None),
36
- **kwargs,
37
- )
38
-
39
-
40
- class OpenAIHalfWrapper(IdentityWrapper):
41
- def __init__(self, *args, **kwargs):
42
- super().__init__(*args, **kwargs)
43
- self.diffusion_model = self.diffusion_model.half()
44
-
45
- def forward(
46
- self, x: torch.Tensor, t: torch.Tensor, c: dict, **kwargs
47
- ) -> torch.Tensor:
48
- x = torch.cat((x, c.get("concat", torch.Tensor([]).type_as(x))), dim=1)
49
- _context = c.get("crossattn", None)
50
- _y = c.get("vector", None)
51
- if _context is not None:
52
- _context = _context.half()
53
- if _y is not None:
54
- _y = _y.half()
55
- x = x.half()
56
- t = t.half()
57
-
58
- out = self.diffusion_model(
59
- x,
60
- timesteps=t,
61
- context=_context,
62
- y=_y,
63
- **kwargs,
64
- )
65
- return out.float()
66
-
67
-
68
- class ControlWrapper(nn.Module):
69
- def __init__(self, diffusion_model, compile_model: bool = False, dtype=torch.float32):
70
- super().__init__()
71
- self.compile = (
72
- torch.compile
73
- if (version.parse(torch.__version__) >= version.parse("2.0.0"))
74
- and compile_model
75
- else lambda x: x
76
- )
77
- self.diffusion_model = self.compile(diffusion_model)
78
- self.control_model = None
79
- self.dtype = dtype
80
-
81
- def load_control_model(self, control_model):
82
- self.control_model = self.compile(control_model)
83
-
84
- def forward(
85
- self, x: torch.Tensor, t: torch.Tensor, c: dict, control_scale=1, **kwargs
86
- ) -> torch.Tensor:
87
- with torch.autocast("cuda", dtype=self.dtype):
88
- control = self.control_model(x=c.get("control", None), timesteps=t, xt=x,
89
- control_vector=c.get("control_vector", None),
90
- mask_x=c.get("mask_x", None),
91
- context=c.get("crossattn", None),
92
- y=c.get("vector", None))
93
- out = self.diffusion_model(
94
- x,
95
- timesteps=t,
96
- context=c.get("crossattn", None),
97
- y=c.get("vector", None),
98
- control=control,
99
- control_scale=control_scale,
100
- **kwargs,
101
- )
102
- return out.float()
103
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/distributions/__init__.py DELETED
File without changes
sgm/modules/distributions/distributions.py DELETED
@@ -1,102 +0,0 @@
1
- import numpy as np
2
- import torch
3
-
4
-
5
- class AbstractDistribution:
6
- def sample(self):
7
- raise NotImplementedError()
8
-
9
- def mode(self):
10
- raise NotImplementedError()
11
-
12
-
13
- class DiracDistribution(AbstractDistribution):
14
- def __init__(self, value):
15
- self.value = value
16
-
17
- def sample(self):
18
- return self.value
19
-
20
- def mode(self):
21
- return self.value
22
-
23
-
24
- class DiagonalGaussianDistribution(object):
25
- def __init__(self, parameters, deterministic=False):
26
- self.parameters = parameters
27
- self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
28
- self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
29
- self.deterministic = deterministic
30
- self.std = torch.exp(0.5 * self.logvar)
31
- self.var = torch.exp(self.logvar)
32
- if self.deterministic:
33
- self.var = self.std = torch.zeros_like(self.mean).to(
34
- device=self.parameters.device
35
- )
36
-
37
- def sample(self):
38
- x = self.mean + self.std * torch.randn(self.mean.shape).to(
39
- device=self.parameters.device
40
- )
41
- return x
42
-
43
- def kl(self, other=None):
44
- if self.deterministic:
45
- return torch.Tensor([0.0])
46
- else:
47
- if other is None:
48
- return 0.5 * torch.sum(
49
- torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar,
50
- dim=[1, 2, 3],
51
- )
52
- else:
53
- return 0.5 * torch.sum(
54
- torch.pow(self.mean - other.mean, 2) / other.var
55
- + self.var / other.var
56
- - 1.0
57
- - self.logvar
58
- + other.logvar,
59
- dim=[1, 2, 3],
60
- )
61
-
62
- def nll(self, sample, dims=[1, 2, 3]):
63
- if self.deterministic:
64
- return torch.Tensor([0.0])
65
- logtwopi = np.log(2.0 * np.pi)
66
- return 0.5 * torch.sum(
67
- logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
68
- dim=dims,
69
- )
70
-
71
- def mode(self):
72
- return self.mean
73
-
74
-
75
- def normal_kl(mean1, logvar1, mean2, logvar2):
76
- """
77
- source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
78
- Compute the KL divergence between two gaussians.
79
- Shapes are automatically broadcasted, so batches can be compared to
80
- scalars, among other use cases.
81
- """
82
- tensor = None
83
- for obj in (mean1, logvar1, mean2, logvar2):
84
- if isinstance(obj, torch.Tensor):
85
- tensor = obj
86
- break
87
- assert tensor is not None, "at least one argument must be a Tensor"
88
-
89
- # Force variances to be Tensors. Broadcasting helps convert scalars to
90
- # Tensors, but it does not work for torch.exp().
91
- logvar1, logvar2 = [
92
- x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
93
- for x in (logvar1, logvar2)
94
- ]
95
-
96
- return 0.5 * (
97
- -1.0
98
- + logvar2
99
- - logvar1
100
- + torch.exp(logvar1 - logvar2)
101
- + ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
102
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/ema.py DELETED
@@ -1,86 +0,0 @@
1
- import torch
2
- from torch import nn
3
-
4
-
5
- class LitEma(nn.Module):
6
- def __init__(self, model, decay=0.9999, use_num_upates=True):
7
- super().__init__()
8
- if decay < 0.0 or decay > 1.0:
9
- raise ValueError("Decay must be between 0 and 1")
10
-
11
- self.m_name2s_name = {}
12
- self.register_buffer("decay", torch.tensor(decay, dtype=torch.float32))
13
- self.register_buffer(
14
- "num_updates",
15
- torch.tensor(0, dtype=torch.int)
16
- if use_num_upates
17
- else torch.tensor(-1, dtype=torch.int),
18
- )
19
-
20
- for name, p in model.named_parameters():
21
- if p.requires_grad:
22
- # remove as '.'-character is not allowed in buffers
23
- s_name = name.replace(".", "")
24
- self.m_name2s_name.update({name: s_name})
25
- self.register_buffer(s_name, p.clone().detach().data)
26
-
27
- self.collected_params = []
28
-
29
- def reset_num_updates(self):
30
- del self.num_updates
31
- self.register_buffer("num_updates", torch.tensor(0, dtype=torch.int))
32
-
33
- def forward(self, model):
34
- decay = self.decay
35
-
36
- if self.num_updates >= 0:
37
- self.num_updates += 1
38
- decay = min(self.decay, (1 + self.num_updates) / (10 + self.num_updates))
39
-
40
- one_minus_decay = 1.0 - decay
41
-
42
- with torch.no_grad():
43
- m_param = dict(model.named_parameters())
44
- shadow_params = dict(self.named_buffers())
45
-
46
- for key in m_param:
47
- if m_param[key].requires_grad:
48
- sname = self.m_name2s_name[key]
49
- shadow_params[sname] = shadow_params[sname].type_as(m_param[key])
50
- shadow_params[sname].sub_(
51
- one_minus_decay * (shadow_params[sname] - m_param[key])
52
- )
53
- else:
54
- assert not key in self.m_name2s_name
55
-
56
- def copy_to(self, model):
57
- m_param = dict(model.named_parameters())
58
- shadow_params = dict(self.named_buffers())
59
- for key in m_param:
60
- if m_param[key].requires_grad:
61
- m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)
62
- else:
63
- assert not key in self.m_name2s_name
64
-
65
- def store(self, parameters):
66
- """
67
- Save the current parameters for restoring later.
68
- Args:
69
- parameters: Iterable of `torch.nn.Parameter`; the parameters to be
70
- temporarily stored.
71
- """
72
- self.collected_params = [param.clone() for param in parameters]
73
-
74
- def restore(self, parameters):
75
- """
76
- Restore the parameters stored with the `store` method.
77
- Useful to validate the model with EMA parameters without affecting the
78
- original optimization process. Store the parameters before the
79
- `copy_to` method. After validation (or model saving), use this to
80
- restore the former parameters.
81
- Args:
82
- parameters: Iterable of `torch.nn.Parameter`; the parameters to be
83
- updated with the stored parameters.
84
- """
85
- for c_param, param in zip(self.collected_params, parameters):
86
- param.data.copy_(c_param.data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/modules/encoders/__init__.py DELETED
File without changes
sgm/modules/encoders/modules.py DELETED
@@ -1,1062 +0,0 @@
1
- from contextlib import nullcontext
2
- from functools import partial
3
- from typing import Dict, List, Optional, Tuple, Union
4
-
5
- import kornia
6
- import numpy as np
7
- import open_clip
8
- import torch
9
- import torch.nn as nn
10
- from einops import rearrange, repeat
11
- from omegaconf import ListConfig
12
- from torch.utils.checkpoint import checkpoint
13
- from transformers import (
14
- ByT5Tokenizer,
15
- CLIPTextModel,
16
- CLIPTokenizer,
17
- T5EncoderModel,
18
- T5Tokenizer,
19
- )
20
-
21
- from ...modules.autoencoding.regularizers import DiagonalGaussianRegularizer
22
- from ...modules.diffusionmodules.model import Encoder
23
- from ...modules.diffusionmodules.openaimodel import Timestep
24
- from ...modules.diffusionmodules.util import extract_into_tensor, make_beta_schedule
25
- from ...modules.distributions.distributions import DiagonalGaussianDistribution
26
- from ...util import (
27
- autocast,
28
- count_params,
29
- default,
30
- disabled_train,
31
- expand_dims_like,
32
- instantiate_from_config,
33
- )
34
-
35
- from CKPT_PTH import SDXL_CLIP1_PATH, SDXL_CLIP2_CKPT_PTH
36
-
37
- class AbstractEmbModel(nn.Module):
38
- def __init__(self):
39
- super().__init__()
40
- self._is_trainable = None
41
- self._ucg_rate = None
42
- self._input_key = None
43
-
44
- @property
45
- def is_trainable(self) -> bool:
46
- return self._is_trainable
47
-
48
- @property
49
- def ucg_rate(self) -> Union[float, torch.Tensor]:
50
- return self._ucg_rate
51
-
52
- @property
53
- def input_key(self) -> str:
54
- return self._input_key
55
-
56
- @is_trainable.setter
57
- def is_trainable(self, value: bool):
58
- self._is_trainable = value
59
-
60
- @ucg_rate.setter
61
- def ucg_rate(self, value: Union[float, torch.Tensor]):
62
- self._ucg_rate = value
63
-
64
- @input_key.setter
65
- def input_key(self, value: str):
66
- self._input_key = value
67
-
68
- @is_trainable.deleter
69
- def is_trainable(self):
70
- del self._is_trainable
71
-
72
- @ucg_rate.deleter
73
- def ucg_rate(self):
74
- del self._ucg_rate
75
-
76
- @input_key.deleter
77
- def input_key(self):
78
- del self._input_key
79
-
80
-
81
- class GeneralConditioner(nn.Module):
82
- OUTPUT_DIM2KEYS = {2: "vector", 3: "crossattn", 4: "concat", 5: "concat"}
83
- KEY2CATDIM = {"vector": 1, "crossattn": 2, "concat": 1, 'control_vector': 1}
84
-
85
- def __init__(self, emb_models: Union[List, ListConfig]):
86
- super().__init__()
87
- embedders = []
88
- for n, embconfig in enumerate(emb_models):
89
- embedder = instantiate_from_config(embconfig)
90
- assert isinstance(
91
- embedder, AbstractEmbModel
92
- ), f"embedder model {embedder.__class__.__name__} has to inherit from AbstractEmbModel"
93
- embedder.is_trainable = embconfig.get("is_trainable", False)
94
- embedder.ucg_rate = embconfig.get("ucg_rate", 0.0)
95
- if not embedder.is_trainable:
96
- embedder.train = disabled_train
97
- for param in embedder.parameters():
98
- param.requires_grad = False
99
- embedder.eval()
100
- print(
101
- f"Initialized embedder #{n}: {embedder.__class__.__name__} "
102
- f"with {count_params(embedder, False)} params. Trainable: {embedder.is_trainable}"
103
- )
104
-
105
- if "input_key" in embconfig:
106
- embedder.input_key = embconfig["input_key"]
107
- elif "input_keys" in embconfig:
108
- embedder.input_keys = embconfig["input_keys"]
109
- else:
110
- raise KeyError(
111
- f"need either 'input_key' or 'input_keys' for embedder {embedder.__class__.__name__}"
112
- )
113
-
114
- embedder.legacy_ucg_val = embconfig.get("legacy_ucg_value", None)
115
- if embedder.legacy_ucg_val is not None:
116
- embedder.ucg_prng = np.random.RandomState()
117
-
118
- embedders.append(embedder)
119
- self.embedders = nn.ModuleList(embedders)
120
-
121
- def possibly_get_ucg_val(self, embedder: AbstractEmbModel, batch: Dict) -> Dict:
122
- assert embedder.legacy_ucg_val is not None
123
- p = embedder.ucg_rate
124
- val = embedder.legacy_ucg_val
125
- for i in range(len(batch[embedder.input_key])):
126
- if embedder.ucg_prng.choice(2, p=[1 - p, p]):
127
- batch[embedder.input_key][i] = val
128
- return batch
129
-
130
- def forward(
131
- self, batch: Dict, force_zero_embeddings: Optional[List] = None
132
- ) -> Dict:
133
- output = dict()
134
- if force_zero_embeddings is None:
135
- force_zero_embeddings = []
136
- for embedder in self.embedders:
137
- embedding_context = nullcontext if embedder.is_trainable else torch.no_grad
138
- with embedding_context():
139
- if hasattr(embedder, "input_key") and (embedder.input_key is not None):
140
- if embedder.legacy_ucg_val is not None:
141
- batch = self.possibly_get_ucg_val(embedder, batch)
142
- emb_out = embedder(batch[embedder.input_key])
143
- elif hasattr(embedder, "input_keys"):
144
- emb_out = embedder(*[batch[k] for k in embedder.input_keys])
145
- assert isinstance(
146
- emb_out, (torch.Tensor, list, tuple)
147
- ), f"encoder outputs must be tensors or a sequence, but got {type(emb_out)}"
148
- if not isinstance(emb_out, (list, tuple)):
149
- emb_out = [emb_out]
150
- for emb in emb_out:
151
- out_key = self.OUTPUT_DIM2KEYS[emb.dim()]
152
- if embedder.ucg_rate > 0.0 and embedder.legacy_ucg_val is None:
153
- emb = (
154
- expand_dims_like(
155
- torch.bernoulli(
156
- (1.0 - embedder.ucg_rate)
157
- * torch.ones(emb.shape[0], device=emb.device)
158
- ),
159
- emb,
160
- )
161
- * emb
162
- )
163
- if (
164
- hasattr(embedder, "input_key")
165
- and embedder.input_key in force_zero_embeddings
166
- ):
167
- emb = torch.zeros_like(emb)
168
- if out_key in output:
169
- output[out_key] = torch.cat(
170
- (output[out_key], emb), self.KEY2CATDIM[out_key]
171
- )
172
- else:
173
- output[out_key] = emb
174
- return output
175
-
176
- def get_unconditional_conditioning(
177
- self, batch_c, batch_uc=None, force_uc_zero_embeddings=None
178
- ):
179
- if force_uc_zero_embeddings is None:
180
- force_uc_zero_embeddings = []
181
- ucg_rates = list()
182
- for embedder in self.embedders:
183
- ucg_rates.append(embedder.ucg_rate)
184
- embedder.ucg_rate = 0.0
185
- c = self(batch_c)
186
- uc = self(batch_c if batch_uc is None else batch_uc, force_uc_zero_embeddings)
187
-
188
- for embedder, rate in zip(self.embedders, ucg_rates):
189
- embedder.ucg_rate = rate
190
- return c, uc
191
-
192
-
193
- class GeneralConditionerWithControl(GeneralConditioner):
194
- def forward(
195
- self, batch: Dict, force_zero_embeddings: Optional[List] = None
196
- ) -> Dict:
197
- output = dict()
198
- if force_zero_embeddings is None:
199
- force_zero_embeddings = []
200
- for embedder in self.embedders:
201
- embedding_context = nullcontext if embedder.is_trainable else torch.no_grad
202
- with embedding_context():
203
- if hasattr(embedder, "input_key") and (embedder.input_key is not None):
204
- if embedder.legacy_ucg_val is not None:
205
- batch = self.possibly_get_ucg_val(embedder, batch)
206
- emb_out = embedder(batch[embedder.input_key])
207
- elif hasattr(embedder, "input_keys"):
208
- emb_out = embedder(*[batch[k] for k in embedder.input_keys])
209
- assert isinstance(
210
- emb_out, (torch.Tensor, list, tuple)
211
- ), f"encoder outputs must be tensors or a sequence, but got {type(emb_out)}"
212
- if not isinstance(emb_out, (list, tuple)):
213
- emb_out = [emb_out]
214
- for emb in emb_out:
215
- if 'control_vector' in embedder.input_key:
216
- out_key = 'control_vector'
217
- else:
218
- out_key = self.OUTPUT_DIM2KEYS[emb.dim()]
219
- if embedder.ucg_rate > 0.0 and embedder.legacy_ucg_val is None:
220
- emb = (
221
- expand_dims_like(
222
- torch.bernoulli(
223
- (1.0 - embedder.ucg_rate)
224
- * torch.ones(emb.shape[0], device=emb.device)
225
- ),
226
- emb,
227
- )
228
- * emb
229
- )
230
- if (
231
- hasattr(embedder, "input_key")
232
- and embedder.input_key in force_zero_embeddings
233
- ):
234
- emb = torch.zeros_like(emb)
235
- if out_key in output:
236
- output[out_key] = torch.cat(
237
- (output[out_key], emb), self.KEY2CATDIM[out_key]
238
- )
239
- else:
240
- output[out_key] = emb
241
-
242
- output["control"] = batch["control"]
243
- return output
244
-
245
-
246
- class PreparedConditioner(nn.Module):
247
- def __init__(self, cond_pth, un_cond_pth=None):
248
- super().__init__()
249
- conditions = torch.load(cond_pth)
250
- for k, v in conditions.items():
251
- self.register_buffer(k, v)
252
- self.un_cond_pth = un_cond_pth
253
- if un_cond_pth is not None:
254
- un_conditions = torch.load(un_cond_pth)
255
- for k, v in un_conditions.items():
256
- self.register_buffer(k+'_uc', v)
257
-
258
-
259
- @torch.no_grad()
260
- def forward(
261
- self, batch: Dict, return_uc=False
262
- ) -> Dict:
263
- output = dict()
264
- for k, v in self.state_dict().items():
265
- if not return_uc:
266
- if k.endswith("_uc"):
267
- continue
268
- else:
269
- output[k] = v.detach().clone().repeat(batch['control'].shape[0], *[1 for _ in range(v.ndim - 1)])
270
- else:
271
- if k.endswith("_uc"):
272
- output[k[:-3]] = v.detach().clone().repeat(batch['control'].shape[0], *[1 for _ in range(v.ndim - 1)])
273
- else:
274
- continue
275
- output["control"] = batch["control"]
276
-
277
- for k, v in output.items():
278
- if isinstance(v, torch.Tensor):
279
- assert (torch.isnan(v).any()) is not None
280
- return output
281
-
282
- def get_unconditional_conditioning(
283
- self, batch_c, batch_uc=None, force_uc_zero_embeddings=None
284
- ):
285
- c = self(batch_c)
286
- if self.un_cond_pth is not None:
287
- uc = self(batch_c, return_uc=True)
288
- else:
289
- uc = None
290
- return c, uc
291
-
292
-
293
-
294
- class InceptionV3(nn.Module):
295
- """Wrapper around the https://github.com/mseitzer/pytorch-fid inception
296
- port with an additional squeeze at the end"""
297
-
298
- def __init__(self, normalize_input=False, **kwargs):
299
- super().__init__()
300
- from pytorch_fid import inception
301
-
302
- kwargs["resize_input"] = True
303
- self.model = inception.InceptionV3(normalize_input=normalize_input, **kwargs)
304
-
305
- def forward(self, inp):
306
- # inp = kornia.geometry.resize(inp, (299, 299),
307
- # interpolation='bicubic',
308
- # align_corners=False,
309
- # antialias=True)
310
- # inp = inp.clamp(min=-1, max=1)
311
-
312
- outp = self.model(inp)
313
-
314
- if len(outp) == 1:
315
- return outp[0].squeeze()
316
-
317
- return outp
318
-
319
-
320
- class IdentityEncoder(AbstractEmbModel):
321
- def encode(self, x):
322
- return x
323
-
324
- def forward(self, x):
325
- return x
326
-
327
-
328
- class ClassEmbedder(AbstractEmbModel):
329
- def __init__(self, embed_dim, n_classes=1000, add_sequence_dim=False):
330
- super().__init__()
331
- self.embedding = nn.Embedding(n_classes, embed_dim)
332
- self.n_classes = n_classes
333
- self.add_sequence_dim = add_sequence_dim
334
-
335
- def forward(self, c):
336
- c = self.embedding(c)
337
- if self.add_sequence_dim:
338
- c = c[:, None, :]
339
- return c
340
-
341
- def get_unconditional_conditioning(self, bs, device="cuda"):
342
- uc_class = (
343
- self.n_classes - 1
344
- ) # 1000 classes --> 0 ... 999, one extra class for ucg (class 1000)
345
- uc = torch.ones((bs,), device=device) * uc_class
346
- uc = {self.key: uc.long()}
347
- return uc
348
-
349
-
350
- class ClassEmbedderForMultiCond(ClassEmbedder):
351
- def forward(self, batch, key=None, disable_dropout=False):
352
- out = batch
353
- key = default(key, self.key)
354
- islist = isinstance(batch[key], list)
355
- if islist:
356
- batch[key] = batch[key][0]
357
- c_out = super().forward(batch, key, disable_dropout)
358
- out[key] = [c_out] if islist else c_out
359
- return out
360
-
361
-
362
- class FrozenT5Embedder(AbstractEmbModel):
363
- """Uses the T5 transformer encoder for text"""
364
-
365
- def __init__(
366
- self, version="google/t5-v1_1-xxl", device="cuda", max_length=77, freeze=True
367
- ): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl
368
- super().__init__()
369
- self.tokenizer = T5Tokenizer.from_pretrained(version)
370
- self.transformer = T5EncoderModel.from_pretrained(version)
371
- self.device = device
372
- self.max_length = max_length
373
- if freeze:
374
- self.freeze()
375
-
376
- def freeze(self):
377
- self.transformer = self.transformer.eval()
378
-
379
- for param in self.parameters():
380
- param.requires_grad = False
381
-
382
- # @autocast
383
- def forward(self, text):
384
- batch_encoding = self.tokenizer(
385
- text,
386
- truncation=True,
387
- max_length=self.max_length,
388
- return_length=True,
389
- return_overflowing_tokens=False,
390
- padding="max_length",
391
- return_tensors="pt",
392
- )
393
- tokens = batch_encoding["input_ids"].to(self.device)
394
- with torch.autocast("cuda", enabled=False):
395
- outputs = self.transformer(input_ids=tokens)
396
- z = outputs.last_hidden_state
397
- return z
398
-
399
- def encode(self, text):
400
- return self(text)
401
-
402
-
403
- class FrozenByT5Embedder(AbstractEmbModel):
404
- """
405
- Uses the ByT5 transformer encoder for text. Is character-aware.
406
- """
407
-
408
- def __init__(
409
- self, version="google/byt5-base", device="cuda", max_length=77, freeze=True
410
- ): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl
411
- super().__init__()
412
- self.tokenizer = ByT5Tokenizer.from_pretrained(version)
413
- self.transformer = T5EncoderModel.from_pretrained(version)
414
- self.device = device
415
- self.max_length = max_length
416
- if freeze:
417
- self.freeze()
418
-
419
- def freeze(self):
420
- self.transformer = self.transformer.eval()
421
-
422
- for param in self.parameters():
423
- param.requires_grad = False
424
-
425
- def forward(self, text):
426
- batch_encoding = self.tokenizer(
427
- text,
428
- truncation=True,
429
- max_length=self.max_length,
430
- return_length=True,
431
- return_overflowing_tokens=False,
432
- padding="max_length",
433
- return_tensors="pt",
434
- )
435
- tokens = batch_encoding["input_ids"].to(self.device)
436
- with torch.autocast("cuda", enabled=False):
437
- outputs = self.transformer(input_ids=tokens)
438
- z = outputs.last_hidden_state
439
- return z
440
-
441
- def encode(self, text):
442
- return self(text)
443
-
444
-
445
- class FrozenCLIPEmbedder(AbstractEmbModel):
446
- """Uses the CLIP transformer encoder for text (from huggingface)"""
447
-
448
- LAYERS = ["last", "pooled", "hidden"]
449
-
450
- def __init__(
451
- self,
452
- version="openai/clip-vit-large-patch14",
453
- device="cuda",
454
- max_length=77,
455
- freeze=True,
456
- layer="last",
457
- layer_idx=None,
458
- always_return_pooled=False,
459
- ): # clip-vit-base-patch32
460
- super().__init__()
461
- assert layer in self.LAYERS
462
- self.tokenizer = CLIPTokenizer.from_pretrained(version if SDXL_CLIP1_PATH is None else SDXL_CLIP1_PATH)
463
- self.transformer = CLIPTextModel.from_pretrained(version if SDXL_CLIP1_PATH is None else SDXL_CLIP1_PATH)
464
- self.device = device
465
- self.max_length = max_length
466
- if freeze:
467
- self.freeze()
468
- self.layer = layer
469
- self.layer_idx = layer_idx
470
- self.return_pooled = always_return_pooled
471
- if layer == "hidden":
472
- assert layer_idx is not None
473
- assert 0 <= abs(layer_idx) <= 12
474
-
475
- def freeze(self):
476
- self.transformer = self.transformer.eval()
477
-
478
- for param in self.parameters():
479
- param.requires_grad = False
480
-
481
- @autocast
482
- def forward(self, text):
483
- batch_encoding = self.tokenizer(
484
- text,
485
- truncation=True,
486
- max_length=self.max_length,
487
- return_length=True,
488
- return_overflowing_tokens=False,
489
- padding="max_length",
490
- return_tensors="pt",
491
- )
492
- tokens = batch_encoding["input_ids"].to(self.device)
493
- outputs = self.transformer(
494
- input_ids=tokens, output_hidden_states=self.layer == "hidden"
495
- )
496
- if self.layer == "last":
497
- z = outputs.last_hidden_state
498
- elif self.layer == "pooled":
499
- z = outputs.pooler_output[:, None, :]
500
- else:
501
- z = outputs.hidden_states[self.layer_idx]
502
- if self.return_pooled:
503
- return z, outputs.pooler_output
504
- return z
505
-
506
- def encode(self, text):
507
- return self(text)
508
-
509
-
510
- class FrozenOpenCLIPEmbedder2(AbstractEmbModel):
511
- """
512
- Uses the OpenCLIP transformer encoder for text
513
- """
514
-
515
- LAYERS = ["pooled", "last", "penultimate"]
516
-
517
- def __init__(
518
- self,
519
- arch="ViT-H-14",
520
- version="laion2b_s32b_b79k",
521
- device="cuda",
522
- max_length=77,
523
- freeze=True,
524
- layer="last",
525
- always_return_pooled=False,
526
- legacy=True,
527
- ):
528
- super().__init__()
529
- assert layer in self.LAYERS
530
- model, _, _ = open_clip.create_model_and_transforms(
531
- arch,
532
- device=torch.device("cpu"),
533
- pretrained=version if SDXL_CLIP2_CKPT_PTH is None else SDXL_CLIP2_CKPT_PTH,
534
- )
535
- del model.visual
536
- self.model = model
537
-
538
- self.device = device
539
- self.max_length = max_length
540
- self.return_pooled = always_return_pooled
541
- if freeze:
542
- self.freeze()
543
- self.layer = layer
544
- if self.layer == "last":
545
- self.layer_idx = 0
546
- elif self.layer == "penultimate":
547
- self.layer_idx = 1
548
- else:
549
- raise NotImplementedError()
550
- self.legacy = legacy
551
-
552
- def freeze(self):
553
- self.model = self.model.eval()
554
- for param in self.parameters():
555
- param.requires_grad = False
556
-
557
- @autocast
558
- def forward(self, text):
559
- tokens = open_clip.tokenize(text)
560
- z = self.encode_with_transformer(tokens.to(self.device))
561
- if not self.return_pooled and self.legacy:
562
- return z
563
- if self.return_pooled:
564
- assert not self.legacy
565
- return z[self.layer], z["pooled"]
566
- return z[self.layer]
567
-
568
- def encode_with_transformer(self, text):
569
- x = self.model.token_embedding(text) # [batch_size, n_ctx, d_model]
570
- x = x + self.model.positional_embedding
571
- x = x.permute(1, 0, 2) # NLD -> LND
572
- x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask)
573
- if self.legacy:
574
- x = x[self.layer]
575
- x = self.model.ln_final(x)
576
- return x
577
- else:
578
- # x is a dict and will stay a dict
579
- o = x["last"]
580
- o = self.model.ln_final(o)
581
- pooled = self.pool(o, text)
582
- x["pooled"] = pooled
583
- return x
584
-
585
- def pool(self, x, text):
586
- # take features from the eot embedding (eot_token is the highest number in each sequence)
587
- x = (
588
- x[torch.arange(x.shape[0]), text.argmax(dim=-1)]
589
- @ self.model.text_projection
590
- )
591
- return x
592
-
593
- def text_transformer_forward(self, x: torch.Tensor, attn_mask=None):
594
- outputs = {}
595
- for i, r in enumerate(self.model.transformer.resblocks):
596
- if i == len(self.model.transformer.resblocks) - 1:
597
- outputs["penultimate"] = x.permute(1, 0, 2) # LND -> NLD
598
- if (
599
- self.model.transformer.grad_checkpointing
600
- and not torch.jit.is_scripting()
601
- ):
602
- x = checkpoint(r, x, attn_mask)
603
- else:
604
- x = r(x, attn_mask=attn_mask)
605
- outputs["last"] = x.permute(1, 0, 2) # LND -> NLD
606
- return outputs
607
-
608
- def encode(self, text):
609
- return self(text)
610
-
611
-
612
- class FrozenOpenCLIPEmbedder(AbstractEmbModel):
613
- LAYERS = [
614
- # "pooled",
615
- "last",
616
- "penultimate",
617
- ]
618
-
619
- def __init__(
620
- self,
621
- arch="ViT-H-14",
622
- version="laion2b_s32b_b79k",
623
- device="cuda",
624
- max_length=77,
625
- freeze=True,
626
- layer="last",
627
- ):
628
- super().__init__()
629
- assert layer in self.LAYERS
630
- model, _, _ = open_clip.create_model_and_transforms(
631
- arch, device=torch.device("cpu"), pretrained=version
632
- )
633
- del model.visual
634
- self.model = model
635
-
636
- self.device = device
637
- self.max_length = max_length
638
- if freeze:
639
- self.freeze()
640
- self.layer = layer
641
- if self.layer == "last":
642
- self.layer_idx = 0
643
- elif self.layer == "penultimate":
644
- self.layer_idx = 1
645
- else:
646
- raise NotImplementedError()
647
-
648
- def freeze(self):
649
- self.model = self.model.eval()
650
- for param in self.parameters():
651
- param.requires_grad = False
652
-
653
- def forward(self, text):
654
- tokens = open_clip.tokenize(text)
655
- z = self.encode_with_transformer(tokens.to(self.device))
656
- return z
657
-
658
- def encode_with_transformer(self, text):
659
- x = self.model.token_embedding(text) # [batch_size, n_ctx, d_model]
660
- x = x + self.model.positional_embedding
661
- x = x.permute(1, 0, 2) # NLD -> LND
662
- x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask)
663
- x = x.permute(1, 0, 2) # LND -> NLD
664
- x = self.model.ln_final(x)
665
- return x
666
-
667
- def text_transformer_forward(self, x: torch.Tensor, attn_mask=None):
668
- for i, r in enumerate(self.model.transformer.resblocks):
669
- if i == len(self.model.transformer.resblocks) - self.layer_idx:
670
- break
671
- if (
672
- self.model.transformer.grad_checkpointing
673
- and not torch.jit.is_scripting()
674
- ):
675
- x = checkpoint(r, x, attn_mask)
676
- else:
677
- x = r(x, attn_mask=attn_mask)
678
- return x
679
-
680
- def encode(self, text):
681
- return self(text)
682
-
683
-
684
- class FrozenOpenCLIPImageEmbedder(AbstractEmbModel):
685
- """
686
- Uses the OpenCLIP vision transformer encoder for images
687
- """
688
-
689
- def __init__(
690
- self,
691
- arch="ViT-H-14",
692
- version="laion2b_s32b_b79k",
693
- device="cuda",
694
- max_length=77,
695
- freeze=True,
696
- antialias=True,
697
- ucg_rate=0.0,
698
- unsqueeze_dim=False,
699
- repeat_to_max_len=False,
700
- num_image_crops=0,
701
- output_tokens=False,
702
- ):
703
- super().__init__()
704
- model, _, _ = open_clip.create_model_and_transforms(
705
- arch,
706
- device=torch.device("cpu"),
707
- pretrained=version,
708
- )
709
- del model.transformer
710
- self.model = model
711
- self.max_crops = num_image_crops
712
- self.pad_to_max_len = self.max_crops > 0
713
- self.repeat_to_max_len = repeat_to_max_len and (not self.pad_to_max_len)
714
- self.device = device
715
- self.max_length = max_length
716
- if freeze:
717
- self.freeze()
718
-
719
- self.antialias = antialias
720
-
721
- self.register_buffer(
722
- "mean", torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False
723
- )
724
- self.register_buffer(
725
- "std", torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False
726
- )
727
- self.ucg_rate = ucg_rate
728
- self.unsqueeze_dim = unsqueeze_dim
729
- self.stored_batch = None
730
- self.model.visual.output_tokens = output_tokens
731
- self.output_tokens = output_tokens
732
-
733
- def preprocess(self, x):
734
- # normalize to [0,1]
735
- x = kornia.geometry.resize(
736
- x,
737
- (224, 224),
738
- interpolation="bicubic",
739
- align_corners=True,
740
- antialias=self.antialias,
741
- )
742
- x = (x + 1.0) / 2.0
743
- # renormalize according to clip
744
- x = kornia.enhance.normalize(x, self.mean, self.std)
745
- return x
746
-
747
- def freeze(self):
748
- self.model = self.model.eval()
749
- for param in self.parameters():
750
- param.requires_grad = False
751
-
752
- @autocast
753
- def forward(self, image, no_dropout=False):
754
- z = self.encode_with_vision_transformer(image)
755
- tokens = None
756
- if self.output_tokens:
757
- z, tokens = z[0], z[1]
758
- z = z.to(image.dtype)
759
- if self.ucg_rate > 0.0 and not no_dropout and not (self.max_crops > 0):
760
- z = (
761
- torch.bernoulli(
762
- (1.0 - self.ucg_rate) * torch.ones(z.shape[0], device=z.device)
763
- )[:, None]
764
- * z
765
- )
766
- if tokens is not None:
767
- tokens = (
768
- expand_dims_like(
769
- torch.bernoulli(
770
- (1.0 - self.ucg_rate)
771
- * torch.ones(tokens.shape[0], device=tokens.device)
772
- ),
773
- tokens,
774
- )
775
- * tokens
776
- )
777
- if self.unsqueeze_dim:
778
- z = z[:, None, :]
779
- if self.output_tokens:
780
- assert not self.repeat_to_max_len
781
- assert not self.pad_to_max_len
782
- return tokens, z
783
- if self.repeat_to_max_len:
784
- if z.dim() == 2:
785
- z_ = z[:, None, :]
786
- else:
787
- z_ = z
788
- return repeat(z_, "b 1 d -> b n d", n=self.max_length), z
789
- elif self.pad_to_max_len:
790
- assert z.dim() == 3
791
- z_pad = torch.cat(
792
- (
793
- z,
794
- torch.zeros(
795
- z.shape[0],
796
- self.max_length - z.shape[1],
797
- z.shape[2],
798
- device=z.device,
799
- ),
800
- ),
801
- 1,
802
- )
803
- return z_pad, z_pad[:, 0, ...]
804
- return z
805
-
806
- def encode_with_vision_transformer(self, img):
807
- # if self.max_crops > 0:
808
- # img = self.preprocess_by_cropping(img)
809
- if img.dim() == 5:
810
- assert self.max_crops == img.shape[1]
811
- img = rearrange(img, "b n c h w -> (b n) c h w")
812
- img = self.preprocess(img)
813
- if not self.output_tokens:
814
- assert not self.model.visual.output_tokens
815
- x = self.model.visual(img)
816
- tokens = None
817
- else:
818
- assert self.model.visual.output_tokens
819
- x, tokens = self.model.visual(img)
820
- if self.max_crops > 0:
821
- x = rearrange(x, "(b n) d -> b n d", n=self.max_crops)
822
- # drop out between 0 and all along the sequence axis
823
- x = (
824
- torch.bernoulli(
825
- (1.0 - self.ucg_rate)
826
- * torch.ones(x.shape[0], x.shape[1], 1, device=x.device)
827
- )
828
- * x
829
- )
830
- if tokens is not None:
831
- tokens = rearrange(tokens, "(b n) t d -> b t (n d)", n=self.max_crops)
832
- print(
833
- f"You are running very experimental token-concat in {self.__class__.__name__}. "
834
- f"Check what you are doing, and then remove this message."
835
- )
836
- if self.output_tokens:
837
- return x, tokens
838
- return x
839
-
840
- def encode(self, text):
841
- return self(text)
842
-
843
-
844
- class FrozenCLIPT5Encoder(AbstractEmbModel):
845
- def __init__(
846
- self,
847
- clip_version="openai/clip-vit-large-patch14",
848
- t5_version="google/t5-v1_1-xl",
849
- device="cuda",
850
- clip_max_length=77,
851
- t5_max_length=77,
852
- ):
853
- super().__init__()
854
- self.clip_encoder = FrozenCLIPEmbedder(
855
- clip_version, device, max_length=clip_max_length
856
- )
857
- self.t5_encoder = FrozenT5Embedder(t5_version, device, max_length=t5_max_length)
858
- print(
859
- f"{self.clip_encoder.__class__.__name__} has {count_params(self.clip_encoder) * 1.e-6:.2f} M parameters, "
860
- f"{self.t5_encoder.__class__.__name__} comes with {count_params(self.t5_encoder) * 1.e-6:.2f} M params."
861
- )
862
-
863
- def encode(self, text):
864
- return self(text)
865
-
866
- def forward(self, text):
867
- clip_z = self.clip_encoder.encode(text)
868
- t5_z = self.t5_encoder.encode(text)
869
- return [clip_z, t5_z]
870
-
871
-
872
- class SpatialRescaler(nn.Module):
873
- def __init__(
874
- self,
875
- n_stages=1,
876
- method="bilinear",
877
- multiplier=0.5,
878
- in_channels=3,
879
- out_channels=None,
880
- bias=False,
881
- wrap_video=False,
882
- kernel_size=1,
883
- remap_output=False,
884
- ):
885
- super().__init__()
886
- self.n_stages = n_stages
887
- assert self.n_stages >= 0
888
- assert method in [
889
- "nearest",
890
- "linear",
891
- "bilinear",
892
- "trilinear",
893
- "bicubic",
894
- "area",
895
- ]
896
- self.multiplier = multiplier
897
- self.interpolator = partial(torch.nn.functional.interpolate, mode=method)
898
- self.remap_output = out_channels is not None or remap_output
899
- if self.remap_output:
900
- print(
901
- f"Spatial Rescaler mapping from {in_channels} to {out_channels} channels after resizing."
902
- )
903
- self.channel_mapper = nn.Conv2d(
904
- in_channels,
905
- out_channels,
906
- kernel_size=kernel_size,
907
- bias=bias,
908
- padding=kernel_size // 2,
909
- )
910
- self.wrap_video = wrap_video
911
-
912
- def forward(self, x):
913
- if self.wrap_video and x.ndim == 5:
914
- B, C, T, H, W = x.shape
915
- x = rearrange(x, "b c t h w -> b t c h w")
916
- x = rearrange(x, "b t c h w -> (b t) c h w")
917
-
918
- for stage in range(self.n_stages):
919
- x = self.interpolator(x, scale_factor=self.multiplier)
920
-
921
- if self.wrap_video:
922
- x = rearrange(x, "(b t) c h w -> b t c h w", b=B, t=T, c=C)
923
- x = rearrange(x, "b t c h w -> b c t h w")
924
- if self.remap_output:
925
- x = self.channel_mapper(x)
926
- return x
927
-
928
- def encode(self, x):
929
- return self(x)
930
-
931
-
932
- class LowScaleEncoder(nn.Module):
933
- def __init__(
934
- self,
935
- model_config,
936
- linear_start,
937
- linear_end,
938
- timesteps=1000,
939
- max_noise_level=250,
940
- output_size=64,
941
- scale_factor=1.0,
942
- ):
943
- super().__init__()
944
- self.max_noise_level = max_noise_level
945
- self.model = instantiate_from_config(model_config)
946
- self.augmentation_schedule = self.register_schedule(
947
- timesteps=timesteps, linear_start=linear_start, linear_end=linear_end
948
- )
949
- self.out_size = output_size
950
- self.scale_factor = scale_factor
951
-
952
- def register_schedule(
953
- self,
954
- beta_schedule="linear",
955
- timesteps=1000,
956
- linear_start=1e-4,
957
- linear_end=2e-2,
958
- cosine_s=8e-3,
959
- ):
960
- betas = make_beta_schedule(
961
- beta_schedule,
962
- timesteps,
963
- linear_start=linear_start,
964
- linear_end=linear_end,
965
- cosine_s=cosine_s,
966
- )
967
- alphas = 1.0 - betas
968
- alphas_cumprod = np.cumprod(alphas, axis=0)
969
- alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
970
-
971
- (timesteps,) = betas.shape
972
- self.num_timesteps = int(timesteps)
973
- self.linear_start = linear_start
974
- self.linear_end = linear_end
975
- assert (
976
- alphas_cumprod.shape[0] == self.num_timesteps
977
- ), "alphas have to be defined for each timestep"
978
-
979
- to_torch = partial(torch.tensor, dtype=torch.float32)
980
-
981
- self.register_buffer("betas", to_torch(betas))
982
- self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod))
983
- self.register_buffer("alphas_cumprod_prev", to_torch(alphas_cumprod_prev))
984
-
985
- # calculations for diffusion q(x_t | x_{t-1}) and others
986
- self.register_buffer("sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod)))
987
- self.register_buffer(
988
- "sqrt_one_minus_alphas_cumprod", to_torch(np.sqrt(1.0 - alphas_cumprod))
989
- )
990
- self.register_buffer(
991
- "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod))
992
- )
993
- self.register_buffer(
994
- "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod))
995
- )
996
- self.register_buffer(
997
- "sqrt_recipm1_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod - 1))
998
- )
999
-
1000
- def q_sample(self, x_start, t, noise=None):
1001
- noise = default(noise, lambda: torch.randn_like(x_start))
1002
- return (
1003
- extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
1004
- + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
1005
- * noise
1006
- )
1007
-
1008
- def forward(self, x):
1009
- z = self.model.encode(x)
1010
- if isinstance(z, DiagonalGaussianDistribution):
1011
- z = z.sample()
1012
- z = z * self.scale_factor
1013
- noise_level = torch.randint(
1014
- 0, self.max_noise_level, (x.shape[0],), device=x.device
1015
- ).long()
1016
- z = self.q_sample(z, noise_level)
1017
- if self.out_size is not None:
1018
- z = torch.nn.functional.interpolate(z, size=self.out_size, mode="nearest")
1019
- # z = z.repeat_interleave(2, -2).repeat_interleave(2, -1)
1020
- return z, noise_level
1021
-
1022
- def decode(self, z):
1023
- z = z / self.scale_factor
1024
- return self.model.decode(z)
1025
-
1026
-
1027
- class ConcatTimestepEmbedderND(AbstractEmbModel):
1028
- """embeds each dimension independently and concatenates them"""
1029
-
1030
- def __init__(self, outdim):
1031
- super().__init__()
1032
- self.timestep = Timestep(outdim)
1033
- self.outdim = outdim
1034
-
1035
- def forward(self, x):
1036
- if x.ndim == 1:
1037
- x = x[:, None]
1038
- assert len(x.shape) == 2
1039
- b, dims = x.shape[0], x.shape[1]
1040
- x = rearrange(x, "b d -> (b d)")
1041
- emb = self.timestep(x)
1042
- emb = rearrange(emb, "(b d) d2 -> b (d d2)", b=b, d=dims, d2=self.outdim)
1043
- return emb
1044
-
1045
-
1046
- class GaussianEncoder(Encoder, AbstractEmbModel):
1047
- def __init__(
1048
- self, weight: float = 1.0, flatten_output: bool = True, *args, **kwargs
1049
- ):
1050
- super().__init__(*args, **kwargs)
1051
- self.posterior = DiagonalGaussianRegularizer()
1052
- self.weight = weight
1053
- self.flatten_output = flatten_output
1054
-
1055
- def forward(self, x) -> Tuple[Dict, torch.Tensor]:
1056
- z = super().forward(x)
1057
- z, log = self.posterior(z)
1058
- log["loss"] = log["kl_loss"]
1059
- log["weight"] = self.weight
1060
- if self.flatten_output:
1061
- z = rearrange(z, "b c h w -> b (h w ) c")
1062
- return log, z
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sgm/util.py DELETED
@@ -1,248 +0,0 @@
1
- import functools
2
- import importlib
3
- import os
4
- from functools import partial
5
- from inspect import isfunction
6
-
7
- import fsspec
8
- import numpy as np
9
- import torch
10
- from PIL import Image, ImageDraw, ImageFont
11
- from safetensors.torch import load_file as load_safetensors
12
-
13
-
14
- def disabled_train(self, mode=True):
15
- """Overwrite model.train with this function to make sure train/eval mode
16
- does not change anymore."""
17
- return self
18
-
19
-
20
- def get_string_from_tuple(s):
21
- try:
22
- # Check if the string starts and ends with parentheses
23
- if s[0] == "(" and s[-1] == ")":
24
- # Convert the string to a tuple
25
- t = eval(s)
26
- # Check if the type of t is tuple
27
- if type(t) == tuple:
28
- return t[0]
29
- else:
30
- pass
31
- except:
32
- pass
33
- return s
34
-
35
-
36
- def is_power_of_two(n):
37
- """
38
- chat.openai.com/chat
39
- Return True if n is a power of 2, otherwise return False.
40
-
41
- The function is_power_of_two takes an integer n as input and returns True if n is a power of 2, otherwise it returns False.
42
- The function works by first checking if n is less than or equal to 0. If n is less than or equal to 0, it can't be a power of 2, so the function returns False.
43
- If n is greater than 0, the function checks whether n is a power of 2 by using a bitwise AND operation between n and n-1. If n is a power of 2, then it will have only one bit set to 1 in its binary representation. When we subtract 1 from a power of 2, all the bits to the right of that bit become 1, and the bit itself becomes 0. So, when we perform a bitwise AND between n and n-1, we get 0 if n is a power of 2, and a non-zero value otherwise.
44
- Thus, if the result of the bitwise AND operation is 0, then n is a power of 2 and the function returns True. Otherwise, the function returns False.
45
-
46
- """
47
- if n <= 0:
48
- return False
49
- return (n & (n - 1)) == 0
50
-
51
-
52
- def autocast(f, enabled=True):
53
- def do_autocast(*args, **kwargs):
54
- with torch.cuda.amp.autocast(
55
- enabled=enabled,
56
- dtype=torch.get_autocast_gpu_dtype(),
57
- cache_enabled=torch.is_autocast_cache_enabled(),
58
- ):
59
- return f(*args, **kwargs)
60
-
61
- return do_autocast
62
-
63
-
64
- def load_partial_from_config(config):
65
- return partial(get_obj_from_str(config["target"]), **config.get("params", dict()))
66
-
67
-
68
- def log_txt_as_img(wh, xc, size=10):
69
- # wh a tuple of (width, height)
70
- # xc a list of captions to plot
71
- b = len(xc)
72
- txts = list()
73
- for bi in range(b):
74
- txt = Image.new("RGB", wh, color="white")
75
- draw = ImageDraw.Draw(txt)
76
- font = ImageFont.truetype("data/DejaVuSans.ttf", size=size)
77
- nc = int(40 * (wh[0] / 256))
78
- if isinstance(xc[bi], list):
79
- text_seq = xc[bi][0]
80
- else:
81
- text_seq = xc[bi]
82
- lines = "\n".join(
83
- text_seq[start : start + nc] for start in range(0, len(text_seq), nc)
84
- )
85
-
86
- try:
87
- draw.text((0, 0), lines, fill="black", font=font)
88
- except UnicodeEncodeError:
89
- print("Cant encode string for logging. Skipping.")
90
-
91
- txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0
92
- txts.append(txt)
93
- txts = np.stack(txts)
94
- txts = torch.tensor(txts)
95
- return txts
96
-
97
-
98
- def partialclass(cls, *args, **kwargs):
99
- class NewCls(cls):
100
- __init__ = functools.partialmethod(cls.__init__, *args, **kwargs)
101
-
102
- return NewCls
103
-
104
-
105
- def make_path_absolute(path):
106
- fs, p = fsspec.core.url_to_fs(path)
107
- if fs.protocol == "file":
108
- return os.path.abspath(p)
109
- return path
110
-
111
-
112
- def ismap(x):
113
- if not isinstance(x, torch.Tensor):
114
- return False
115
- return (len(x.shape) == 4) and (x.shape[1] > 3)
116
-
117
-
118
- def isimage(x):
119
- if not isinstance(x, torch.Tensor):
120
- return False
121
- return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
122
-
123
-
124
- def isheatmap(x):
125
- if not isinstance(x, torch.Tensor):
126
- return False
127
-
128
- return x.ndim == 2
129
-
130
-
131
- def isneighbors(x):
132
- if not isinstance(x, torch.Tensor):
133
- return False
134
- return x.ndim == 5 and (x.shape[2] == 3 or x.shape[2] == 1)
135
-
136
-
137
- def exists(x):
138
- return x is not None
139
-
140
-
141
- def expand_dims_like(x, y):
142
- while x.dim() != y.dim():
143
- x = x.unsqueeze(-1)
144
- return x
145
-
146
-
147
- def default(val, d):
148
- if exists(val):
149
- return val
150
- return d() if isfunction(d) else d
151
-
152
-
153
- def mean_flat(tensor):
154
- """
155
- https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86
156
- Take the mean over all non-batch dimensions.
157
- """
158
- return tensor.mean(dim=list(range(1, len(tensor.shape))))
159
-
160
-
161
- def count_params(model, verbose=False):
162
- total_params = sum(p.numel() for p in model.parameters())
163
- if verbose:
164
- print(f"{model.__class__.__name__} has {total_params * 1.e-6:.2f} M params.")
165
- return total_params
166
-
167
-
168
- def instantiate_from_config(config):
169
- if not "target" in config:
170
- if config == "__is_first_stage__":
171
- return None
172
- elif config == "__is_unconditional__":
173
- return None
174
- raise KeyError("Expected key `target` to instantiate.")
175
- return get_obj_from_str(config["target"])(**config.get("params", dict()))
176
-
177
-
178
- def get_obj_from_str(string, reload=False, invalidate_cache=True):
179
- module, cls = string.rsplit(".", 1)
180
- if invalidate_cache:
181
- importlib.invalidate_caches()
182
- if reload:
183
- module_imp = importlib.import_module(module)
184
- importlib.reload(module_imp)
185
- return getattr(importlib.import_module(module, package=None), cls)
186
-
187
-
188
- def append_zero(x):
189
- return torch.cat([x, x.new_zeros([1])])
190
-
191
-
192
- def append_dims(x, target_dims):
193
- """Appends dimensions to the end of a tensor until it has target_dims dimensions."""
194
- dims_to_append = target_dims - x.ndim
195
- if dims_to_append < 0:
196
- raise ValueError(
197
- f"input has {x.ndim} dims but target_dims is {target_dims}, which is less"
198
- )
199
- return x[(...,) + (None,) * dims_to_append]
200
-
201
-
202
- def load_model_from_config(config, ckpt, verbose=True, freeze=True):
203
- print(f"Loading model from {ckpt}")
204
- if ckpt.endswith("ckpt"):
205
- pl_sd = torch.load(ckpt, map_location="cpu")
206
- if "global_step" in pl_sd:
207
- print(f"Global Step: {pl_sd['global_step']}")
208
- sd = pl_sd["state_dict"]
209
- elif ckpt.endswith("safetensors"):
210
- sd = load_safetensors(ckpt)
211
- else:
212
- raise NotImplementedError
213
-
214
- model = instantiate_from_config(config.model)
215
-
216
- m, u = model.load_state_dict(sd, strict=False)
217
-
218
- if len(m) > 0 and verbose:
219
- print("missing keys:")
220
- print(m)
221
- if len(u) > 0 and verbose:
222
- print("unexpected keys:")
223
- print(u)
224
-
225
- if freeze:
226
- for param in model.parameters():
227
- param.requires_grad = False
228
-
229
- model.eval()
230
- return model
231
-
232
-
233
- def get_configs_path() -> str:
234
- """
235
- Get the `configs` directory.
236
- For a working copy, this is the one in the root of the repository,
237
- but for an installed copy, it's in the `sgm` package (see pyproject.toml).
238
- """
239
- this_dir = os.path.dirname(__file__)
240
- candidates = (
241
- os.path.join(this_dir, "configs"),
242
- os.path.join(this_dir, "..", "configs"),
243
- )
244
- for candidate in candidates:
245
- candidate = os.path.abspath(candidate)
246
- if os.path.isdir(candidate):
247
- return candidate
248
- raise FileNotFoundError(f"Could not find SGM configs in {candidates}")