autoencoder.py 7.48 KB
Newer Older
comfyanonymous's avatar
comfyanonymous committed
1
2
import torch
from contextlib import contextmanager
comfyanonymous's avatar
comfyanonymous committed
3
from typing import Any, Dict, List, Optional, Tuple, Union
comfyanonymous's avatar
comfyanonymous committed
4

comfyanonymous's avatar
comfyanonymous committed
5
from comfy.ldm.modules.distributions.distributions import DiagonalGaussianDistribution
comfyanonymous's avatar
comfyanonymous committed
6

comfyanonymous's avatar
comfyanonymous committed
7
8
from comfy.ldm.util import instantiate_from_config
from comfy.ldm.modules.ema import LitEma
9
import comfy.ops
comfyanonymous's avatar
comfyanonymous committed
10

comfyanonymous's avatar
comfyanonymous committed
11
12
class DiagonalGaussianRegularizer(torch.nn.Module):
    def __init__(self, sample: bool = True):
comfyanonymous's avatar
comfyanonymous committed
13
        super().__init__()
comfyanonymous's avatar
comfyanonymous committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
        self.sample = sample

    def get_trainable_parameters(self) -> Any:
        yield from ()

    def forward(self, z: torch.Tensor) -> Tuple[torch.Tensor, dict]:
        log = dict()
        posterior = DiagonalGaussianDistribution(z)
        if self.sample:
            z = posterior.sample()
        else:
            z = posterior.mode()
        kl_loss = posterior.kl()
        kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]
        log["kl_loss"] = kl_loss
        return z, log


class AbstractAutoencoder(torch.nn.Module):
    """
    This is the base class for all autoencoders, including image autoencoders, image autoencoders with discriminators,
    unCLIP models, etc. Hence, it is fairly general, and specific features
    (e.g. discriminator training, encoding, decoding) must be implemented in subclasses.
    """

    def __init__(
        self,
        ema_decay: Union[None, float] = None,
        monitor: Union[None, str] = None,
        input_key: str = "jpg",
        **kwargs,
    ):
        super().__init__()

        self.input_key = input_key
        self.use_ema = ema_decay is not None
comfyanonymous's avatar
comfyanonymous committed
50
51
52
53
54
        if monitor is not None:
            self.monitor = monitor

        if self.use_ema:
            self.model_ema = LitEma(self, decay=ema_decay)
comfyanonymous's avatar
comfyanonymous committed
55
            logpy.info(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
comfyanonymous's avatar
comfyanonymous committed
56

comfyanonymous's avatar
comfyanonymous committed
57
58
    def get_input(self, batch) -> Any:
        raise NotImplementedError()
comfyanonymous's avatar
comfyanonymous committed
59

comfyanonymous's avatar
comfyanonymous committed
60
61
62
63
    def on_train_batch_end(self, *args, **kwargs):
        # for EMA computation
        if self.use_ema:
            self.model_ema(self)
comfyanonymous's avatar
comfyanonymous committed
64
65
66
67
68
69
70

    @contextmanager
    def ema_scope(self, context=None):
        if self.use_ema:
            self.model_ema.store(self.parameters())
            self.model_ema.copy_to(self)
            if context is not None:
comfyanonymous's avatar
comfyanonymous committed
71
                logpy.info(f"{context}: Switched to EMA weights")
comfyanonymous's avatar
comfyanonymous committed
72
73
74
75
76
77
        try:
            yield None
        finally:
            if self.use_ema:
                self.model_ema.restore(self.parameters())
                if context is not None:
comfyanonymous's avatar
comfyanonymous committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
                    logpy.info(f"{context}: Restored training weights")

    def encode(self, *args, **kwargs) -> torch.Tensor:
        raise NotImplementedError("encode()-method of abstract base class called")

    def decode(self, *args, **kwargs) -> torch.Tensor:
        raise NotImplementedError("decode()-method of abstract base class called")

    def instantiate_optimizer_from_config(self, params, lr, cfg):
        logpy.info(f"loading >>> {cfg['target']} <<< optimizer from config")
        return get_obj_from_str(cfg["target"])(
            params, lr=lr, **cfg.get("params", dict())
        )

    def configure_optimizers(self) -> Any:
        raise NotImplementedError()


class AutoencodingEngine(AbstractAutoencoder):
    """
    Base class for all image autoencoders that we train, like VQGAN or AutoencoderKL
    (we also restore them explicitly as special cases for legacy reasons).
    Regularizations such as KL or VQ are moved to the regularizer class.
    """

    def __init__(
        self,
        *args,
        encoder_config: Dict,
        decoder_config: Dict,
        regularizer_config: Dict,
        **kwargs,
    ):
        super().__init__(*args, **kwargs)

        self.encoder: torch.nn.Module = instantiate_from_config(encoder_config)
        self.decoder: torch.nn.Module = instantiate_from_config(decoder_config)
        self.regularization: AbstractRegularizer = instantiate_from_config(
            regularizer_config
        )
comfyanonymous's avatar
comfyanonymous committed
118
119

    def get_last_layer(self):
comfyanonymous's avatar
comfyanonymous committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
        return self.decoder.get_last_layer()

    def encode(
        self,
        x: torch.Tensor,
        return_reg_log: bool = False,
        unregularized: bool = False,
    ) -> Union[torch.Tensor, Tuple[torch.Tensor, dict]]:
        z = self.encoder(x)
        if unregularized:
            return z, dict()
        z, reg_log = self.regularization(z)
        if return_reg_log:
            return z, reg_log
        return z

    def decode(self, z: torch.Tensor, **kwargs) -> torch.Tensor:
        x = self.decoder(z, **kwargs)
comfyanonymous's avatar
comfyanonymous committed
138
139
        return x

comfyanonymous's avatar
comfyanonymous committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
    def forward(
        self, x: torch.Tensor, **additional_decode_kwargs
    ) -> Tuple[torch.Tensor, torch.Tensor, dict]:
        z, reg_log = self.encode(x, return_reg_log=True)
        dec = self.decode(z, **additional_decode_kwargs)
        return z, dec, reg_log


class AutoencodingEngineLegacy(AutoencodingEngine):
    def __init__(self, embed_dim: int, **kwargs):
        self.max_batch_size = kwargs.pop("max_batch_size", None)
        ddconfig = kwargs.pop("ddconfig")
        super().__init__(
            encoder_config={
                "target": "comfy.ldm.modules.diffusionmodules.model.Encoder",
                "params": ddconfig,
            },
            decoder_config={
                "target": "comfy.ldm.modules.diffusionmodules.model.Decoder",
                "params": ddconfig,
            },
            **kwargs,
        )
163
        self.quant_conv = comfy.ops.disable_weight_init.Conv2d(
comfyanonymous's avatar
comfyanonymous committed
164
165
166
167
            (1 + ddconfig["double_z"]) * ddconfig["z_channels"],
            (1 + ddconfig["double_z"]) * embed_dim,
            1,
        )
168
        self.post_quant_conv = comfy.ops.disable_weight_init.Conv2d(embed_dim, ddconfig["z_channels"], 1)
comfyanonymous's avatar
comfyanonymous committed
169
        self.embed_dim = embed_dim
comfyanonymous's avatar
comfyanonymous committed
170

comfyanonymous's avatar
comfyanonymous committed
171
172
173
    def get_autoencoder_params(self) -> list:
        params = super().get_autoencoder_params()
        return params
comfyanonymous's avatar
comfyanonymous committed
174

comfyanonymous's avatar
comfyanonymous committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
    def encode(
        self, x: torch.Tensor, return_reg_log: bool = False
    ) -> Union[torch.Tensor, Tuple[torch.Tensor, dict]]:
        if self.max_batch_size is None:
            z = self.encoder(x)
            z = self.quant_conv(z)
        else:
            N = x.shape[0]
            bs = self.max_batch_size
            n_batches = int(math.ceil(N / bs))
            z = list()
            for i_batch in range(n_batches):
                z_batch = self.encoder(x[i_batch * bs : (i_batch + 1) * bs])
                z_batch = self.quant_conv(z_batch)
                z.append(z_batch)
            z = torch.cat(z, 0)

        z, reg_log = self.regularization(z)
        if return_reg_log:
            return z, reg_log
        return z

    def decode(self, z: torch.Tensor, **decoder_kwargs) -> torch.Tensor:
        if self.max_batch_size is None:
            dec = self.post_quant_conv(z)
            dec = self.decoder(dec, **decoder_kwargs)
        else:
            N = z.shape[0]
            bs = self.max_batch_size
            n_batches = int(math.ceil(N / bs))
            dec = list()
            for i_batch in range(n_batches):
                dec_batch = self.post_quant_conv(z[i_batch * bs : (i_batch + 1) * bs])
                dec_batch = self.decoder(dec_batch, **decoder_kwargs)
                dec.append(dec_batch)
            dec = torch.cat(dec, 0)
comfyanonymous's avatar
comfyanonymous committed
211

comfyanonymous's avatar
comfyanonymous committed
212
        return dec
comfyanonymous's avatar
comfyanonymous committed
213
214


comfyanonymous's avatar
comfyanonymous committed
215
216
217
218
219
220
221
222
223
224
225
226
class AutoencoderKL(AutoencodingEngineLegacy):
    def __init__(self, **kwargs):
        if "lossconfig" in kwargs:
            kwargs["loss_config"] = kwargs.pop("lossconfig")
        super().__init__(
            regularizer_config={
                "target": (
                    "comfy.ldm.models.autoencoder.DiagonalGaussianRegularizer"
                )
            },
            **kwargs,
        )