File size: 6,840 Bytes
3ed0796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
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
import torch
from torch.utils.checkpoint import checkpoint
from diffusers.models.autoencoders.autoencoder_kl import Encoder, Decoder, AutoencoderKL
from typing import Optional

class MyEncoder(Encoder):
    def __init__(
        self, 
        in_channels = 3, 
        out_channels = 3, 
        down_block_types = ..., 
        block_out_channels = ..., 
        layers_per_block = 2, 
        norm_num_groups = 32, 
        act_fn = "silu", 
        double_z = True, 
        mid_block_add_attention=True
    ):
        super().__init__(
            in_channels, out_channels, down_block_types, block_out_channels, 
            layers_per_block, norm_num_groups, act_fn, double_z, mid_block_add_attention
        )

    def forward(self, sample: torch.Tensor) -> torch.Tensor:
        r"""The forward method of the `Encoder` class."""

        sample = self.conv_in(sample)

        if torch.is_grad_enabled() and self.gradient_checkpointing:
            # down
            for down_block in self.down_blocks:
                sample = checkpoint(self.ckpt_wrapper(down_block), sample)
            # middle
            sample = checkpoint(self.ckpt_wrapper(self.mid_block), sample)

        else:
            # down
            for down_block in self.down_blocks:
                sample = down_block(sample)

            # middle
            sample = self.mid_block(sample)

        # post-process
        sample = self.conv_norm_out(sample)
        sample = self.conv_act(sample)
        sample = self.conv_out(sample)

        return sample
    
    def ckpt_wrapper(self, module):
        def ckpt_forward(*inputs):
            outputs = module(*inputs)
            return outputs
        return ckpt_forward


class MyDecoder(Decoder):
    def __init__(
        self, 
        in_channels = 3, 
        out_channels = 3, 
        up_block_types = ..., 
        block_out_channels = ..., 
        layers_per_block = 2, 
        norm_num_groups = 32, 
        act_fn = "silu", 
        norm_type = "group", 
        mid_block_add_attention=True
    ):
        super().__init__(
            in_channels, out_channels, up_block_types, block_out_channels, 
            layers_per_block, norm_num_groups, act_fn, norm_type, mid_block_add_attention
        )
    
    def forward(
        self,
        sample: torch.Tensor,
        latent_embeds: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        r"""The forward method of the `Decoder` class."""

        sample = self.conv_in(sample)

        upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
        if torch.is_grad_enabled() and self.gradient_checkpointing:
            # middle
            sample = checkpoint(self.ckpt_wrapper(self.mid_block), sample, latent_embeds)
            sample = sample.to(upscale_dtype)

            # up
            for up_block in self.up_blocks:
                sample = checkpoint(self.ckpt_wrapper(up_block), sample, latent_embeds)
        else:
            # middle
            sample = self.mid_block(sample, latent_embeds)
            sample = sample.to(upscale_dtype)

            # up
            for up_block in self.up_blocks:
                sample = up_block(sample, latent_embeds)

        # post-process
        if latent_embeds is None:
            sample = self.conv_norm_out(sample)
        else:
            sample = self.conv_norm_out(sample, latent_embeds)
        sample = self.conv_act(sample)
        sample = self.conv_out(sample)

        return sample

    def ckpt_wrapper(self, module):
        def ckpt_forward(*inputs):
            outputs = module(*inputs)
            return outputs
        return ckpt_forward


class MyAutoencoderKL(AutoencoderKL):
    def __init__(
        self, 
        in_channels = 3, 
        out_channels = 3, 
        down_block_types = ..., 
        up_block_types = ..., 
        block_out_channels = ..., 
        layers_per_block = 1, 
        act_fn = "silu", 
        latent_channels = 4, 
        norm_num_groups = 32, 
        sample_size = 32, 
        scaling_factor = 0.18215, 
        shift_factor = None, 
        latents_mean = None, 
        latents_std = None, 
        force_upcast = True, 
        use_quant_conv = True, 
        use_post_quant_conv = True, 
        mid_block_add_attention = True,
        bn_momentum = 0.1, 
    ):
        super().__init__(
            in_channels, out_channels, down_block_types, up_block_types, block_out_channels, 
            layers_per_block, act_fn, latent_channels, norm_num_groups, sample_size, 
            scaling_factor, shift_factor, latents_mean, latents_std, force_upcast, 
            use_quant_conv, use_post_quant_conv, mid_block_add_attention
        )
        self.encoder = MyEncoder(
            in_channels=in_channels,
            out_channels=latent_channels,
            down_block_types=down_block_types,
            block_out_channels=block_out_channels,
            layers_per_block=layers_per_block,
            act_fn=act_fn,
            norm_num_groups=norm_num_groups,
            double_z=True,
            mid_block_add_attention=mid_block_add_attention,
        )

        # pass init params to Decoder
        self.decoder = MyDecoder(
            in_channels=latent_channels,
            out_channels=out_channels,
            up_block_types=up_block_types,
            block_out_channels=block_out_channels,
            layers_per_block=layers_per_block,
            norm_num_groups=norm_num_groups,
            act_fn=act_fn,
            mid_block_add_attention=mid_block_add_attention,
        )
        self.bn = torch.nn.BatchNorm2d(
            latent_channels, eps=1e-4, momentum=bn_momentum, affine=False, track_running_stats=True
        )
        self.bn.reset_running_stats()
        self.init_bn()
        

    def init_bn(self):
        # self.bn.running_mean = torch.zeros_like(self.bn.running_mean).to(torch.float64)
        # self.bn.running_var = torch.ones_like(self.bn.running_var).to(torch.float64) / self.config.scaling_factor ** 2
        self.bn.running_mean = torch.zeros_like(self.bn.running_mean)
        self.bn.running_var = torch.ones_like(self.bn.running_var) / self.config.scaling_factor ** 2

    @property
    def mean(self):
        mean = self.bn.running_mean.unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
        return mean
    
    @property
    def std(self):
        std = self.bn.running_var.sqrt().unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
        return std
    

    def forward(self, x: torch.Tensor, use_checkpoint=False):
        self.encoder.gradient_checkpointing = use_checkpoint
        self.decoder.gradient_checkpointing = use_checkpoint
        posterior = self.encode(x).latent_dist
        z = posterior.sample()
        latent = self.bn(z)
        recon = self.decode(z).sample
        return posterior, latent, recon