"vscode:/vscode.git/clone" did not exist on "aa9bcaf04c520b5fd0aa8d6d807b8090ea43d61c"
autoencoder_asym_kl.py 7.61 KB
Newer Older
1
# Copyright 2024 The HuggingFace Team. All rights reserved.
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

19
20
21
22
from ...configuration_utils import ConfigMixin, register_to_config
from ...utils.accelerate_utils import apply_forward_hook
from ..modeling_outputs import AutoencoderKLOutput
from ..modeling_utils import ModelMixin
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
23
24
25
26
27
from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder, MaskConditionDecoder


class AsymmetricAutoencoderKL(ModelMixin, ConfigMixin):
    r"""
Quentin Gallouédec's avatar
Quentin Gallouédec committed
28
29
    Designing a Better Asymmetric VQGAN for StableDiffusion https://huggingface.co/papers/2306.04632 . A VAE model with
    KL loss for encoding images into latents and decoding latent representations into images.
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

    This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
    for all models (such as downloading or saving).

    Parameters:
        in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
        out_channels (int,  *optional*, defaults to 3): Number of channels in the output.
        down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
            Tuple of downsample block types.
        down_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
            Tuple of down block output channels.
        layers_per_down_block (`int`, *optional*, defaults to `1`):
            Number layers for down block.
        up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
            Tuple of upsample block types.
        up_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
            Tuple of up block output channels.
        layers_per_up_block (`int`, *optional*, defaults to `1`):
            Number layers for up block.
        act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
        latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
        sample_size (`int`, *optional*, defaults to `32`): Sample input size.
        norm_num_groups (`int`, *optional*, defaults to `32`):
            Number of groups to use for the first normalization layer in ResNet blocks.
        scaling_factor (`float`, *optional*, defaults to 0.18215):
            The component-wise standard deviation of the trained latent space computed using the first batch of the
            training set. This is used to scale the latent space to have unit variance when training the diffusion
            model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
            diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
            / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
Quentin Gallouédec's avatar
Quentin Gallouédec committed
60
            Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752) paper.
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
61
62
    """

Aryan's avatar
Aryan committed
63
64
    _skip_layerwise_casting_patterns = ["decoder"]

Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
65
66
67
68
69
    @register_to_config
    def __init__(
        self,
        in_channels: int = 3,
        out_channels: int = 3,
70
71
        down_block_types: Tuple[str, ...] = ("DownEncoderBlock2D",),
        down_block_out_channels: Tuple[int, ...] = (64,),
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
72
        layers_per_down_block: int = 1,
73
74
        up_block_types: Tuple[str, ...] = ("UpDecoderBlock2D",),
        up_block_out_channels: Tuple[int, ...] = (64,),
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
75
76
77
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
        layers_per_up_block: int = 1,
        act_fn: str = "silu",
        latent_channels: int = 4,
        norm_num_groups: int = 32,
        sample_size: int = 32,
        scaling_factor: float = 0.18215,
    ) -> None:
        super().__init__()

        # pass init params to Encoder
        self.encoder = Encoder(
            in_channels=in_channels,
            out_channels=latent_channels,
            down_block_types=down_block_types,
            block_out_channels=down_block_out_channels,
            layers_per_block=layers_per_down_block,
            act_fn=act_fn,
            norm_num_groups=norm_num_groups,
            double_z=True,
        )

        # pass init params to Decoder
        self.decoder = MaskConditionDecoder(
            in_channels=latent_channels,
            out_channels=out_channels,
            up_block_types=up_block_types,
            block_out_channels=up_block_out_channels,
            layers_per_block=layers_per_up_block,
            act_fn=act_fn,
            norm_num_groups=norm_num_groups,
        )

        self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
        self.post_quant_conv = nn.Conv2d(latent_channels, latent_channels, 1)

        self.use_slicing = False
        self.use_tiling = False

113
114
115
        self.register_to_config(block_out_channels=up_block_out_channels)
        self.register_to_config(force_upcast=False)

Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
116
    @apply_forward_hook
117
    def encode(self, x: torch.Tensor, return_dict: bool = True) -> Union[AutoencoderKLOutput, Tuple[torch.Tensor]]:
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
118
119
120
121
122
123
124
125
126
127
128
        h = self.encoder(x)
        moments = self.quant_conv(h)
        posterior = DiagonalGaussianDistribution(moments)

        if not return_dict:
            return (posterior,)

        return AutoencoderKLOutput(latent_dist=posterior)

    def _decode(
        self,
129
130
131
        z: torch.Tensor,
        image: Optional[torch.Tensor] = None,
        mask: Optional[torch.Tensor] = None,
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
132
        return_dict: bool = True,
133
    ) -> Union[DecoderOutput, Tuple[torch.Tensor]]:
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
134
135
136
137
138
139
140
141
142
143
144
        z = self.post_quant_conv(z)
        dec = self.decoder(z, image, mask)

        if not return_dict:
            return (dec,)

        return DecoderOutput(sample=dec)

    @apply_forward_hook
    def decode(
        self,
145
        z: torch.Tensor,
146
        generator: Optional[torch.Generator] = None,
147
148
        image: Optional[torch.Tensor] = None,
        mask: Optional[torch.Tensor] = None,
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
149
        return_dict: bool = True,
150
    ) -> Union[DecoderOutput, Tuple[torch.Tensor]]:
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
151
152
153
154
155
156
157
158
159
        decoded = self._decode(z, image, mask).sample

        if not return_dict:
            return (decoded,)

        return DecoderOutput(sample=decoded)

    def forward(
        self,
160
161
        sample: torch.Tensor,
        mask: Optional[torch.Tensor] = None,
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
162
163
164
        sample_posterior: bool = False,
        return_dict: bool = True,
        generator: Optional[torch.Generator] = None,
165
    ) -> Union[DecoderOutput, Tuple[torch.Tensor]]:
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
166
167
        r"""
        Args:
168
169
            sample (`torch.Tensor`): Input sample.
            mask (`torch.Tensor`, *optional*, defaults to `None`): Optional inpainting mask.
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
170
171
172
173
174
175
176
177
178
179
180
            sample_posterior (`bool`, *optional*, defaults to `False`):
                Whether to sample from the posterior.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
        """
        x = sample
        posterior = self.encode(x).latent_dist
        if sample_posterior:
            z = posterior.sample(generator=generator)
        else:
            z = posterior.mode()
181
        dec = self.decode(z, generator, sample, mask).sample
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
182
183
184
185
186

        if not return_dict:
            return (dec,)

        return DecoderOutput(sample=dec)