InvokeAI 2.2.4.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. backend/__init__.py +0 -0
  2. backend/invoke_ai_web_server.py +1724 -0
  3. backend/modules/__init__.py +0 -0
  4. backend/modules/create_cmd_parser.py +55 -0
  5. backend/modules/get_canvas_generation_mode.py +117 -0
  6. backend/modules/parameters.py +71 -0
  7. backend/modules/parse_seed_weights.py +47 -0
  8. configs/INITIAL_MODELS.yaml +80 -0
  9. configs/models.yaml.example +29 -0
  10. configs/sd-concepts.txt +803 -0
  11. configs/stable-diffusion/v1-finetune.yaml +110 -0
  12. configs/stable-diffusion/v1-finetune_style.yaml +103 -0
  13. configs/stable-diffusion/v1-inference.yaml +79 -0
  14. configs/stable-diffusion/v1-inpainting-inference.yaml +79 -0
  15. configs/stable-diffusion/v1-m1-finetune.yaml +110 -0
  16. docs/assets/invoke-web-server-1.png +0 -0
  17. docs/assets/invoke_ai_banner.png +0 -0
  18. invokeai-2.2.4.5.data/data/assets/caution.png +0 -0
  19. invokeai-2.2.4.5.data/data/configs/INITIAL_MODELS.yaml +80 -0
  20. invokeai-2.2.4.5.data/data/configs/models.yaml.example +29 -0
  21. invokeai-2.2.4.5.data/data/configs/sd-concepts.txt +803 -0
  22. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-finetune.yaml +110 -0
  23. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-finetune_style.yaml +103 -0
  24. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-inference.yaml +79 -0
  25. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-inpainting-inference.yaml +79 -0
  26. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-m1-finetune.yaml +110 -0
  27. invokeai-2.2.4.5.data/data/frontend/dist/assets/Inter-Bold.790c108b.ttf +0 -0
  28. invokeai-2.2.4.5.data/data/frontend/dist/assets/Inter.b9a8e5e2.ttf +0 -0
  29. invokeai-2.2.4.5.data/data/frontend/dist/assets/favicon.0d253ced.ico +0 -0
  30. invokeai-2.2.4.5.data/data/frontend/dist/assets/index-legacy-b741077f.js +48 -0
  31. invokeai-2.2.4.5.data/data/frontend/dist/assets/index.0dadf5d0.css +1 -0
  32. invokeai-2.2.4.5.data/data/frontend/dist/assets/index.21ff81eb.js +625 -0
  33. invokeai-2.2.4.5.data/data/frontend/dist/assets/logo.13003d72.png +0 -0
  34. invokeai-2.2.4.5.data/data/frontend/dist/assets/polyfills-legacy-dde3a68a.js +4 -0
  35. invokeai-2.2.4.5.data/data/frontend/dist/assets/polyfills.1ff60148.js +1 -0
  36. invokeai-2.2.4.5.data/data/frontend/dist/index.html +23 -0
  37. invokeai-2.2.4.5.data/data/scripts/configure_invokeai.py +797 -0
  38. invokeai-2.2.4.5.data/data/scripts/create_root.py +43 -0
  39. invokeai-2.2.4.5.data/data/scripts/dream.py +10 -0
  40. invokeai-2.2.4.5.data/data/scripts/images2prompt.py +30 -0
  41. invokeai-2.2.4.5.data/data/scripts/invoke.py +5 -0
  42. invokeai-2.2.4.5.data/data/scripts/legacy_api.py +681 -0
  43. invokeai-2.2.4.5.data/data/scripts/load_models.py +12 -0
  44. invokeai-2.2.4.5.data/data/scripts/merge_embeddings.py +124 -0
  45. invokeai-2.2.4.5.data/data/scripts/preload_models.py +12 -0
  46. invokeai-2.2.4.5.data/data/scripts/sd-metadata.py +22 -0
  47. invokeai-2.2.4.5.dist-info/LICENSE +21 -0
  48. invokeai-2.2.4.5.dist-info/LICENSE-ModelWeights.txt +294 -0
  49. invokeai-2.2.4.5.dist-info/METADATA +288 -0
  50. invokeai-2.2.4.5.dist-info/RECORD +169 -0
  51. invokeai-2.2.4.5.dist-info/WHEEL +5 -0
  52. invokeai-2.2.4.5.dist-info/entry_points.txt +4 -0
  53. invokeai-2.2.4.5.dist-info/top_level.txt +6 -0
  54. invokeai-2.2.4.5.dist-info/zip-safe +1 -0
  55. ldm/__init__.py +0 -0
  56. ldm/data/__init__.py +0 -0
  57. ldm/data/base.py +31 -0
  58. ldm/data/imagenet.py +466 -0
  59. ldm/data/lsun.py +126 -0
  60. ldm/data/personalized.py +202 -0
  61. ldm/data/personalized_style.py +169 -0
  62. ldm/generate.py +1159 -0
  63. ldm/invoke/CLI.py +960 -0
  64. ldm/invoke/__init__.py +3 -0
  65. ldm/invoke/args.py +1257 -0
  66. ldm/invoke/concepts_lib.py +169 -0
  67. ldm/invoke/conditioning.py +289 -0
  68. ldm/invoke/devices.py +27 -0
  69. ldm/invoke/generator/__init__.py +4 -0
  70. ldm/invoke/generator/base.py +335 -0
  71. ldm/invoke/generator/embiggen.py +501 -0
  72. ldm/invoke/generator/img2img.py +97 -0
  73. ldm/invoke/generator/inpaint.py +358 -0
  74. ldm/invoke/generator/omnibus.py +175 -0
  75. ldm/invoke/generator/txt2img.py +88 -0
  76. ldm/invoke/generator/txt2img2img.py +182 -0
  77. ldm/invoke/globals.py +31 -0
  78. ldm/invoke/image_util.py +70 -0
  79. ldm/invoke/log.py +66 -0
  80. ldm/invoke/model_cache.py +449 -0
  81. ldm/invoke/patchmatch.py +44 -0
  82. ldm/invoke/pngwriter.py +113 -0
  83. ldm/invoke/prompt_parser.py +655 -0
  84. ldm/invoke/readline.py +442 -0
  85. ldm/invoke/restoration/__init__.py +4 -0
  86. ldm/invoke/restoration/base.py +38 -0
  87. ldm/invoke/restoration/codeformer.py +103 -0
  88. ldm/invoke/restoration/codeformer_arch.py +276 -0
  89. ldm/invoke/restoration/gfpgan.py +84 -0
  90. ldm/invoke/restoration/outcrop.py +108 -0
  91. ldm/invoke/restoration/outpaint.py +92 -0
  92. ldm/invoke/restoration/realesrgan.py +90 -0
  93. ldm/invoke/restoration/vqgan_arch.py +435 -0
  94. ldm/invoke/seamless.py +30 -0
  95. ldm/invoke/server.py +282 -0
  96. ldm/invoke/server_legacy.py +246 -0
  97. ldm/invoke/txt2mask.py +136 -0
  98. ldm/lr_scheduler.py +143 -0
  99. ldm/models/__init__.py +0 -0
  100. ldm/models/autoencoder.py +596 -0
  101. ldm/models/diffusion/__init__.py +0 -0
  102. ldm/models/diffusion/classifier.py +355 -0
  103. ldm/models/diffusion/cross_attention_control.py +443 -0
  104. ldm/models/diffusion/cross_attention_map_saving.py +95 -0
  105. ldm/models/diffusion/ddim.py +111 -0
  106. ldm/models/diffusion/ddpm.py +2263 -0
  107. ldm/models/diffusion/ksampler.py +312 -0
  108. ldm/models/diffusion/plms.py +146 -0
  109. ldm/models/diffusion/sampler.py +450 -0
  110. ldm/models/diffusion/shared_invokeai_diffusion.py +244 -0
  111. ldm/modules/__init__.py +0 -0
  112. ldm/modules/attention.py +274 -0
  113. ldm/modules/diffusionmodules/__init__.py +0 -0
  114. ldm/modules/diffusionmodules/model.py +894 -0
  115. ldm/modules/diffusionmodules/openaimodel.py +1036 -0
  116. ldm/modules/diffusionmodules/util.py +314 -0
  117. ldm/modules/distributions/__init__.py +0 -0
  118. ldm/modules/distributions/distributions.py +104 -0
  119. ldm/modules/ema.py +88 -0
  120. ldm/modules/embedding_manager.py +413 -0
  121. ldm/modules/encoders/__init__.py +0 -0
  122. ldm/modules/encoders/modules.py +772 -0
  123. ldm/modules/image_degradation/__init__.py +6 -0
  124. ldm/modules/image_degradation/bsrgan.py +846 -0
  125. ldm/modules/image_degradation/bsrgan_light.py +751 -0
  126. ldm/modules/image_degradation/utils_image.py +1024 -0
  127. ldm/modules/losses/__init__.py +1 -0
  128. ldm/modules/losses/contperceptual.py +175 -0
  129. ldm/modules/losses/vqperceptual.py +240 -0
  130. ldm/modules/x_transformer.py +752 -0
  131. ldm/simplet2i.py +13 -0
  132. ldm/util.py +264 -0
  133. scripts/configure_invokeai.py +797 -0
  134. scripts/create_root.py +43 -0
  135. scripts/dream.py +10 -0
  136. scripts/images2prompt.py +30 -0
  137. scripts/invoke.py +5 -0
  138. scripts/legacy_api.py +681 -0
  139. scripts/load_models.py +12 -0
  140. scripts/merge_embeddings.py +124 -0
  141. scripts/orig_scripts/img2img.py +296 -0
  142. scripts/orig_scripts/inpaint.py +98 -0
  143. scripts/orig_scripts/knn2img.py +397 -0
  144. scripts/orig_scripts/sample_diffusion.py +313 -0
  145. scripts/orig_scripts/train_searcher.py +147 -0
  146. scripts/orig_scripts/txt2img.py +324 -0
  147. scripts/preload_models.py +12 -0
  148. scripts/sd-metadata.py +22 -0
  149. vendored/clip/clip/__init__.py +1 -0
  150. vendored/clip/clip/bpe_simple_vocab_16e6.txt.gz +0 -0
  151. vendored/clip/clip/clip.py +237 -0
  152. vendored/clip/clip/model.py +436 -0
  153. vendored/clip/clip/simple_tokenizer.py +132 -0
  154. vendored/clip/hubconf.py +42 -0
  155. vendored/clip/setup.py +21 -0
  156. vendored/clip/tests/test_consistency.py +25 -0
  157. vendored/clipseg/datasets/coco_wrapper.py +99 -0
  158. vendored/clipseg/datasets/pascal_zeroshot.py +60 -0
  159. vendored/clipseg/datasets/pfe_dataset.py +129 -0
  160. vendored/clipseg/datasets/phrasecut.py +380 -0
  161. vendored/clipseg/datasets/utils.py +68 -0
  162. vendored/clipseg/evaluation_utils.py +292 -0
  163. vendored/clipseg/general_utils.py +272 -0
  164. vendored/clipseg/metrics.py +271 -0
  165. vendored/clipseg/models/clipseg.py +538 -0
  166. vendored/clipseg/models/vitseg.py +286 -0
  167. vendored/clipseg/score.py +453 -0
  168. vendored/clipseg/setup.py +30 -0
  169. vendored/clipseg/training.py +266 -0
@@ -0,0 +1 @@
1
+ from ldm.modules.losses.contperceptual import LPIPSWithDiscriminator
@@ -0,0 +1,175 @@
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from taming.modules.losses.vqperceptual import * # TODO: taming dependency yes/no?
5
+
6
+
7
+ class LPIPSWithDiscriminator(nn.Module):
8
+ def __init__(
9
+ self,
10
+ disc_start,
11
+ logvar_init=0.0,
12
+ kl_weight=1.0,
13
+ pixelloss_weight=1.0,
14
+ disc_num_layers=3,
15
+ disc_in_channels=3,
16
+ disc_factor=1.0,
17
+ disc_weight=1.0,
18
+ perceptual_weight=1.0,
19
+ use_actnorm=False,
20
+ disc_conditional=False,
21
+ disc_loss='hinge',
22
+ ):
23
+
24
+ super().__init__()
25
+ assert disc_loss in ['hinge', 'vanilla']
26
+ self.kl_weight = kl_weight
27
+ self.pixel_weight = pixelloss_weight
28
+ self.perceptual_loss = LPIPS().eval()
29
+ self.perceptual_weight = perceptual_weight
30
+ # output log variance
31
+ self.logvar = nn.Parameter(torch.ones(size=()) * logvar_init)
32
+
33
+ self.discriminator = NLayerDiscriminator(
34
+ input_nc=disc_in_channels,
35
+ n_layers=disc_num_layers,
36
+ use_actnorm=use_actnorm,
37
+ ).apply(weights_init)
38
+ self.discriminator_iter_start = disc_start
39
+ self.disc_loss = (
40
+ hinge_d_loss if disc_loss == 'hinge' else vanilla_d_loss
41
+ )
42
+ self.disc_factor = disc_factor
43
+ self.discriminator_weight = disc_weight
44
+ self.disc_conditional = disc_conditional
45
+
46
+ def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None):
47
+ if last_layer is not None:
48
+ nll_grads = torch.autograd.grad(
49
+ nll_loss, last_layer, retain_graph=True
50
+ )[0]
51
+ g_grads = torch.autograd.grad(
52
+ g_loss, last_layer, retain_graph=True
53
+ )[0]
54
+ else:
55
+ nll_grads = torch.autograd.grad(
56
+ nll_loss, self.last_layer[0], retain_graph=True
57
+ )[0]
58
+ g_grads = torch.autograd.grad(
59
+ g_loss, self.last_layer[0], retain_graph=True
60
+ )[0]
61
+
62
+ d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
63
+ d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
64
+ d_weight = d_weight * self.discriminator_weight
65
+ return d_weight
66
+
67
+ def forward(
68
+ self,
69
+ inputs,
70
+ reconstructions,
71
+ posteriors,
72
+ optimizer_idx,
73
+ global_step,
74
+ last_layer=None,
75
+ cond=None,
76
+ split='train',
77
+ weights=None,
78
+ ):
79
+ rec_loss = torch.abs(
80
+ inputs.contiguous() - reconstructions.contiguous()
81
+ )
82
+ if self.perceptual_weight > 0:
83
+ p_loss = self.perceptual_loss(
84
+ inputs.contiguous(), reconstructions.contiguous()
85
+ )
86
+ rec_loss = rec_loss + self.perceptual_weight * p_loss
87
+
88
+ nll_loss = rec_loss / torch.exp(self.logvar) + self.logvar
89
+ weighted_nll_loss = nll_loss
90
+ if weights is not None:
91
+ weighted_nll_loss = weights * nll_loss
92
+ weighted_nll_loss = (
93
+ torch.sum(weighted_nll_loss) / weighted_nll_loss.shape[0]
94
+ )
95
+ nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]
96
+ kl_loss = posteriors.kl()
97
+ kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]
98
+
99
+ # now the GAN part
100
+ if optimizer_idx == 0:
101
+ # generator update
102
+ if cond is None:
103
+ assert not self.disc_conditional
104
+ logits_fake = self.discriminator(reconstructions.contiguous())
105
+ else:
106
+ assert self.disc_conditional
107
+ logits_fake = self.discriminator(
108
+ torch.cat((reconstructions.contiguous(), cond), dim=1)
109
+ )
110
+ g_loss = -torch.mean(logits_fake)
111
+
112
+ if self.disc_factor > 0.0:
113
+ try:
114
+ d_weight = self.calculate_adaptive_weight(
115
+ nll_loss, g_loss, last_layer=last_layer
116
+ )
117
+ except RuntimeError:
118
+ assert not self.training
119
+ d_weight = torch.tensor(0.0)
120
+ else:
121
+ d_weight = torch.tensor(0.0)
122
+
123
+ disc_factor = adopt_weight(
124
+ self.disc_factor,
125
+ global_step,
126
+ threshold=self.discriminator_iter_start,
127
+ )
128
+ loss = (
129
+ weighted_nll_loss
130
+ + self.kl_weight * kl_loss
131
+ + d_weight * disc_factor * g_loss
132
+ )
133
+
134
+ log = {
135
+ '{}/total_loss'.format(split): loss.clone().detach().mean(),
136
+ '{}/logvar'.format(split): self.logvar.detach(),
137
+ '{}/kl_loss'.format(split): kl_loss.detach().mean(),
138
+ '{}/nll_loss'.format(split): nll_loss.detach().mean(),
139
+ '{}/rec_loss'.format(split): rec_loss.detach().mean(),
140
+ '{}/d_weight'.format(split): d_weight.detach(),
141
+ '{}/disc_factor'.format(split): torch.tensor(disc_factor),
142
+ '{}/g_loss'.format(split): g_loss.detach().mean(),
143
+ }
144
+ return loss, log
145
+
146
+ if optimizer_idx == 1:
147
+ # second pass for discriminator update
148
+ if cond is None:
149
+ logits_real = self.discriminator(inputs.contiguous().detach())
150
+ logits_fake = self.discriminator(
151
+ reconstructions.contiguous().detach()
152
+ )
153
+ else:
154
+ logits_real = self.discriminator(
155
+ torch.cat((inputs.contiguous().detach(), cond), dim=1)
156
+ )
157
+ logits_fake = self.discriminator(
158
+ torch.cat(
159
+ (reconstructions.contiguous().detach(), cond), dim=1
160
+ )
161
+ )
162
+
163
+ disc_factor = adopt_weight(
164
+ self.disc_factor,
165
+ global_step,
166
+ threshold=self.discriminator_iter_start,
167
+ )
168
+ d_loss = disc_factor * self.disc_loss(logits_real, logits_fake)
169
+
170
+ log = {
171
+ '{}/disc_loss'.format(split): d_loss.clone().detach().mean(),
172
+ '{}/logits_real'.format(split): logits_real.detach().mean(),
173
+ '{}/logits_fake'.format(split): logits_fake.detach().mean(),
174
+ }
175
+ return d_loss, log
@@ -0,0 +1,240 @@
1
+ import torch
2
+ from torch import nn
3
+ import torch.nn.functional as F
4
+ from einops import repeat
5
+
6
+ from taming.modules.discriminator.model import (
7
+ NLayerDiscriminator,
8
+ weights_init,
9
+ )
10
+ from taming.modules.losses.lpips import LPIPS
11
+ from taming.modules.losses.vqperceptual import hinge_d_loss, vanilla_d_loss
12
+
13
+
14
+ def hinge_d_loss_with_exemplar_weights(logits_real, logits_fake, weights):
15
+ assert weights.shape[0] == logits_real.shape[0] == logits_fake.shape[0]
16
+ loss_real = torch.mean(F.relu(1.0 - logits_real), dim=[1, 2, 3])
17
+ loss_fake = torch.mean(F.relu(1.0 + logits_fake), dim=[1, 2, 3])
18
+ loss_real = (weights * loss_real).sum() / weights.sum()
19
+ loss_fake = (weights * loss_fake).sum() / weights.sum()
20
+ d_loss = 0.5 * (loss_real + loss_fake)
21
+ return d_loss
22
+
23
+
24
+ def adopt_weight(weight, global_step, threshold=0, value=0.0):
25
+ if global_step < threshold:
26
+ weight = value
27
+ return weight
28
+
29
+
30
+ def measure_perplexity(predicted_indices, n_embed):
31
+ # src: https://github.com/karpathy/deep-vector-quantization/blob/main/model.py
32
+ # eval cluster perplexity. when perplexity == num_embeddings then all clusters are used exactly equally
33
+ encodings = (
34
+ F.one_hot(predicted_indices, n_embed).float().reshape(-1, n_embed)
35
+ )
36
+ avg_probs = encodings.mean(0)
37
+ perplexity = (-(avg_probs * torch.log(avg_probs + 1e-10)).sum()).exp()
38
+ cluster_use = torch.sum(avg_probs > 0)
39
+ return perplexity, cluster_use
40
+
41
+
42
+ def l1(x, y):
43
+ return torch.abs(x - y)
44
+
45
+
46
+ def l2(x, y):
47
+ return torch.pow((x - y), 2)
48
+
49
+
50
+ class VQLPIPSWithDiscriminator(nn.Module):
51
+ def __init__(
52
+ self,
53
+ disc_start,
54
+ codebook_weight=1.0,
55
+ pixelloss_weight=1.0,
56
+ disc_num_layers=3,
57
+ disc_in_channels=3,
58
+ disc_factor=1.0,
59
+ disc_weight=1.0,
60
+ perceptual_weight=1.0,
61
+ use_actnorm=False,
62
+ disc_conditional=False,
63
+ disc_ndf=64,
64
+ disc_loss='hinge',
65
+ n_classes=None,
66
+ perceptual_loss='lpips',
67
+ pixel_loss='l1',
68
+ ):
69
+ super().__init__()
70
+ assert disc_loss in ['hinge', 'vanilla']
71
+ assert perceptual_loss in ['lpips', 'clips', 'dists']
72
+ assert pixel_loss in ['l1', 'l2']
73
+ self.codebook_weight = codebook_weight
74
+ self.pixel_weight = pixelloss_weight
75
+ if perceptual_loss == 'lpips':
76
+ print(f'{self.__class__.__name__}: Running with LPIPS.')
77
+ self.perceptual_loss = LPIPS().eval()
78
+ else:
79
+ raise ValueError(
80
+ f'Unknown perceptual loss: >> {perceptual_loss} <<'
81
+ )
82
+ self.perceptual_weight = perceptual_weight
83
+
84
+ if pixel_loss == 'l1':
85
+ self.pixel_loss = l1
86
+ else:
87
+ self.pixel_loss = l2
88
+
89
+ self.discriminator = NLayerDiscriminator(
90
+ input_nc=disc_in_channels,
91
+ n_layers=disc_num_layers,
92
+ use_actnorm=use_actnorm,
93
+ ndf=disc_ndf,
94
+ ).apply(weights_init)
95
+ self.discriminator_iter_start = disc_start
96
+ if disc_loss == 'hinge':
97
+ self.disc_loss = hinge_d_loss
98
+ elif disc_loss == 'vanilla':
99
+ self.disc_loss = vanilla_d_loss
100
+ else:
101
+ raise ValueError(f"Unknown GAN loss '{disc_loss}'.")
102
+ print(f'VQLPIPSWithDiscriminator running with {disc_loss} loss.')
103
+ self.disc_factor = disc_factor
104
+ self.discriminator_weight = disc_weight
105
+ self.disc_conditional = disc_conditional
106
+ self.n_classes = n_classes
107
+
108
+ def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None):
109
+ if last_layer is not None:
110
+ nll_grads = torch.autograd.grad(
111
+ nll_loss, last_layer, retain_graph=True
112
+ )[0]
113
+ g_grads = torch.autograd.grad(
114
+ g_loss, last_layer, retain_graph=True
115
+ )[0]
116
+ else:
117
+ nll_grads = torch.autograd.grad(
118
+ nll_loss, self.last_layer[0], retain_graph=True
119
+ )[0]
120
+ g_grads = torch.autograd.grad(
121
+ g_loss, self.last_layer[0], retain_graph=True
122
+ )[0]
123
+
124
+ d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
125
+ d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
126
+ d_weight = d_weight * self.discriminator_weight
127
+ return d_weight
128
+
129
+ def forward(
130
+ self,
131
+ codebook_loss,
132
+ inputs,
133
+ reconstructions,
134
+ optimizer_idx,
135
+ global_step,
136
+ last_layer=None,
137
+ cond=None,
138
+ split='train',
139
+ predicted_indices=None,
140
+ ):
141
+ if not exists(codebook_loss):
142
+ codebook_loss = torch.tensor([0.0]).to(inputs.device)
143
+ # rec_loss = torch.abs(inputs.contiguous() - reconstructions.contiguous())
144
+ rec_loss = self.pixel_loss(
145
+ inputs.contiguous(), reconstructions.contiguous()
146
+ )
147
+ if self.perceptual_weight > 0:
148
+ p_loss = self.perceptual_loss(
149
+ inputs.contiguous(), reconstructions.contiguous()
150
+ )
151
+ rec_loss = rec_loss + self.perceptual_weight * p_loss
152
+ else:
153
+ p_loss = torch.tensor([0.0])
154
+
155
+ nll_loss = rec_loss
156
+ # nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]
157
+ nll_loss = torch.mean(nll_loss)
158
+
159
+ # now the GAN part
160
+ if optimizer_idx == 0:
161
+ # generator update
162
+ if cond is None:
163
+ assert not self.disc_conditional
164
+ logits_fake = self.discriminator(reconstructions.contiguous())
165
+ else:
166
+ assert self.disc_conditional
167
+ logits_fake = self.discriminator(
168
+ torch.cat((reconstructions.contiguous(), cond), dim=1)
169
+ )
170
+ g_loss = -torch.mean(logits_fake)
171
+
172
+ try:
173
+ d_weight = self.calculate_adaptive_weight(
174
+ nll_loss, g_loss, last_layer=last_layer
175
+ )
176
+ except RuntimeError:
177
+ assert not self.training
178
+ d_weight = torch.tensor(0.0)
179
+
180
+ disc_factor = adopt_weight(
181
+ self.disc_factor,
182
+ global_step,
183
+ threshold=self.discriminator_iter_start,
184
+ )
185
+ loss = (
186
+ nll_loss
187
+ + d_weight * disc_factor * g_loss
188
+ + self.codebook_weight * codebook_loss.mean()
189
+ )
190
+
191
+ log = {
192
+ '{}/total_loss'.format(split): loss.clone().detach().mean(),
193
+ '{}/quant_loss'.format(split): codebook_loss.detach().mean(),
194
+ '{}/nll_loss'.format(split): nll_loss.detach().mean(),
195
+ '{}/rec_loss'.format(split): rec_loss.detach().mean(),
196
+ '{}/p_loss'.format(split): p_loss.detach().mean(),
197
+ '{}/d_weight'.format(split): d_weight.detach(),
198
+ '{}/disc_factor'.format(split): torch.tensor(disc_factor),
199
+ '{}/g_loss'.format(split): g_loss.detach().mean(),
200
+ }
201
+ if predicted_indices is not None:
202
+ assert self.n_classes is not None
203
+ with torch.no_grad():
204
+ perplexity, cluster_usage = measure_perplexity(
205
+ predicted_indices, self.n_classes
206
+ )
207
+ log[f'{split}/perplexity'] = perplexity
208
+ log[f'{split}/cluster_usage'] = cluster_usage
209
+ return loss, log
210
+
211
+ if optimizer_idx == 1:
212
+ # second pass for discriminator update
213
+ if cond is None:
214
+ logits_real = self.discriminator(inputs.contiguous().detach())
215
+ logits_fake = self.discriminator(
216
+ reconstructions.contiguous().detach()
217
+ )
218
+ else:
219
+ logits_real = self.discriminator(
220
+ torch.cat((inputs.contiguous().detach(), cond), dim=1)
221
+ )
222
+ logits_fake = self.discriminator(
223
+ torch.cat(
224
+ (reconstructions.contiguous().detach(), cond), dim=1
225
+ )
226
+ )
227
+
228
+ disc_factor = adopt_weight(
229
+ self.disc_factor,
230
+ global_step,
231
+ threshold=self.discriminator_iter_start,
232
+ )
233
+ d_loss = disc_factor * self.disc_loss(logits_real, logits_fake)
234
+
235
+ log = {
236
+ '{}/disc_loss'.format(split): d_loss.clone().detach().mean(),
237
+ '{}/logits_real'.format(split): logits_real.detach().mean(),
238
+ '{}/logits_fake'.format(split): logits_fake.detach().mean(),
239
+ }
240
+ return d_loss, log