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
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates. All rights reserved.
|
| 2 |
+
# Copyright (c) 2024 Black Forest Labs and The XLabs-AI Team. All rights reserved.
|
| 3 |
+
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from einops import rearrange
|
| 20 |
+
from torch import Tensor, nn
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class AutoEncoderParams:
|
| 25 |
+
resolution: int
|
| 26 |
+
in_channels: int
|
| 27 |
+
ch: int
|
| 28 |
+
out_ch: int
|
| 29 |
+
ch_mult: list[int]
|
| 30 |
+
num_res_blocks: int
|
| 31 |
+
z_channels: int
|
| 32 |
+
scale_factor: float
|
| 33 |
+
shift_factor: float
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def swish(x: Tensor) -> Tensor:
|
| 37 |
+
return x * torch.sigmoid(x)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class AttnBlock(nn.Module):
|
| 41 |
+
def __init__(self, in_channels: int):
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.in_channels = in_channels
|
| 44 |
+
|
| 45 |
+
self.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
| 46 |
+
|
| 47 |
+
self.q = nn.Conv2d(in_channels, in_channels, kernel_size=1)
|
| 48 |
+
self.k = nn.Conv2d(in_channels, in_channels, kernel_size=1)
|
| 49 |
+
self.v = nn.Conv2d(in_channels, in_channels, kernel_size=1)
|
| 50 |
+
self.proj_out = nn.Conv2d(in_channels, in_channels, kernel_size=1)
|
| 51 |
+
|
| 52 |
+
def attention(self, h_: Tensor) -> Tensor:
|
| 53 |
+
h_ = self.norm(h_)
|
| 54 |
+
q = self.q(h_)
|
| 55 |
+
k = self.k(h_)
|
| 56 |
+
v = self.v(h_)
|
| 57 |
+
|
| 58 |
+
b, c, h, w = q.shape
|
| 59 |
+
q = rearrange(q, "b c h w -> b 1 (h w) c").contiguous()
|
| 60 |
+
k = rearrange(k, "b c h w -> b 1 (h w) c").contiguous()
|
| 61 |
+
v = rearrange(v, "b c h w -> b 1 (h w) c").contiguous()
|
| 62 |
+
h_ = nn.functional.scaled_dot_product_attention(q, k, v)
|
| 63 |
+
|
| 64 |
+
return rearrange(h_, "b 1 (h w) c -> b c h w", h=h, w=w, c=c, b=b)
|
| 65 |
+
|
| 66 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 67 |
+
return x + self.proj_out(self.attention(x))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class ResnetBlock(nn.Module):
|
| 71 |
+
def __init__(self, in_channels: int, out_channels: int):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.in_channels = in_channels
|
| 74 |
+
out_channels = in_channels if out_channels is None else out_channels
|
| 75 |
+
self.out_channels = out_channels
|
| 76 |
+
|
| 77 |
+
self.norm1 = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
| 78 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
| 79 |
+
self.norm2 = nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True)
|
| 80 |
+
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
| 81 |
+
if self.in_channels != self.out_channels:
|
| 82 |
+
self.nin_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
|
| 83 |
+
|
| 84 |
+
def forward(self, x):
|
| 85 |
+
h = x
|
| 86 |
+
h = self.norm1(h)
|
| 87 |
+
h = swish(h)
|
| 88 |
+
h = self.conv1(h)
|
| 89 |
+
|
| 90 |
+
h = self.norm2(h)
|
| 91 |
+
h = swish(h)
|
| 92 |
+
h = self.conv2(h)
|
| 93 |
+
|
| 94 |
+
if self.in_channels != self.out_channels:
|
| 95 |
+
x = self.nin_shortcut(x)
|
| 96 |
+
|
| 97 |
+
return x + h
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class Downsample(nn.Module):
|
| 101 |
+
def __init__(self, in_channels: int):
|
| 102 |
+
super().__init__()
|
| 103 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
| 104 |
+
self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
|
| 105 |
+
|
| 106 |
+
def forward(self, x: Tensor):
|
| 107 |
+
pad = (0, 1, 0, 1)
|
| 108 |
+
x = nn.functional.pad(x, pad, mode="constant", value=0)
|
| 109 |
+
x = self.conv(x)
|
| 110 |
+
return x
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class Upsample(nn.Module):
|
| 114 |
+
def __init__(self, in_channels: int):
|
| 115 |
+
super().__init__()
|
| 116 |
+
self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
|
| 117 |
+
|
| 118 |
+
def forward(self, x: Tensor):
|
| 119 |
+
x = nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
|
| 120 |
+
x = self.conv(x)
|
| 121 |
+
return x
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class Encoder(nn.Module):
|
| 125 |
+
def __init__(
|
| 126 |
+
self,
|
| 127 |
+
resolution: int,
|
| 128 |
+
in_channels: int,
|
| 129 |
+
ch: int,
|
| 130 |
+
ch_mult: list[int],
|
| 131 |
+
num_res_blocks: int,
|
| 132 |
+
z_channels: int,
|
| 133 |
+
):
|
| 134 |
+
super().__init__()
|
| 135 |
+
self.ch = ch
|
| 136 |
+
self.num_resolutions = len(ch_mult)
|
| 137 |
+
self.num_res_blocks = num_res_blocks
|
| 138 |
+
self.resolution = resolution
|
| 139 |
+
self.in_channels = in_channels
|
| 140 |
+
# downsampling
|
| 141 |
+
self.conv_in = nn.Conv2d(in_channels, self.ch, kernel_size=3, stride=1, padding=1)
|
| 142 |
+
|
| 143 |
+
curr_res = resolution
|
| 144 |
+
in_ch_mult = (1,) + tuple(ch_mult)
|
| 145 |
+
self.in_ch_mult = in_ch_mult
|
| 146 |
+
self.down = nn.ModuleList()
|
| 147 |
+
block_in = self.ch
|
| 148 |
+
for i_level in range(self.num_resolutions):
|
| 149 |
+
block = nn.ModuleList()
|
| 150 |
+
attn = nn.ModuleList()
|
| 151 |
+
block_in = ch * in_ch_mult[i_level]
|
| 152 |
+
block_out = ch * ch_mult[i_level]
|
| 153 |
+
for _ in range(self.num_res_blocks):
|
| 154 |
+
block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))
|
| 155 |
+
block_in = block_out
|
| 156 |
+
down = nn.Module()
|
| 157 |
+
down.block = block
|
| 158 |
+
down.attn = attn
|
| 159 |
+
if i_level != self.num_resolutions - 1:
|
| 160 |
+
down.downsample = Downsample(block_in)
|
| 161 |
+
curr_res = curr_res // 2
|
| 162 |
+
self.down.append(down)
|
| 163 |
+
|
| 164 |
+
# middle
|
| 165 |
+
self.mid = nn.Module()
|
| 166 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)
|
| 167 |
+
self.mid.attn_1 = AttnBlock(block_in)
|
| 168 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)
|
| 169 |
+
|
| 170 |
+
# end
|
| 171 |
+
self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
|
| 172 |
+
self.conv_out = nn.Conv2d(block_in, 2 * z_channels, kernel_size=3, stride=1, padding=1)
|
| 173 |
+
|
| 174 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 175 |
+
# downsampling
|
| 176 |
+
hs = [self.conv_in(x)]
|
| 177 |
+
for i_level in range(self.num_resolutions):
|
| 178 |
+
for i_block in range(self.num_res_blocks):
|
| 179 |
+
h = self.down[i_level].block[i_block](hs[-1])
|
| 180 |
+
if len(self.down[i_level].attn) > 0:
|
| 181 |
+
h = self.down[i_level].attn[i_block](h)
|
| 182 |
+
hs.append(h)
|
| 183 |
+
if i_level != self.num_resolutions - 1:
|
| 184 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
| 185 |
+
|
| 186 |
+
# middle
|
| 187 |
+
h = hs[-1]
|
| 188 |
+
h = self.mid.block_1(h)
|
| 189 |
+
h = self.mid.attn_1(h)
|
| 190 |
+
h = self.mid.block_2(h)
|
| 191 |
+
# end
|
| 192 |
+
h = self.norm_out(h)
|
| 193 |
+
h = swish(h)
|
| 194 |
+
h = self.conv_out(h)
|
| 195 |
+
return h
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class Decoder(nn.Module):
|
| 199 |
+
def __init__(
|
| 200 |
+
self,
|
| 201 |
+
ch: int,
|
| 202 |
+
out_ch: int,
|
| 203 |
+
ch_mult: list[int],
|
| 204 |
+
num_res_blocks: int,
|
| 205 |
+
in_channels: int,
|
| 206 |
+
resolution: int,
|
| 207 |
+
z_channels: int,
|
| 208 |
+
):
|
| 209 |
+
super().__init__()
|
| 210 |
+
self.ch = ch
|
| 211 |
+
self.num_resolutions = len(ch_mult)
|
| 212 |
+
self.num_res_blocks = num_res_blocks
|
| 213 |
+
self.resolution = resolution
|
| 214 |
+
self.in_channels = in_channels
|
| 215 |
+
self.ffactor = 2 ** (self.num_resolutions - 1)
|
| 216 |
+
|
| 217 |
+
# compute in_ch_mult, block_in and curr_res at lowest res
|
| 218 |
+
block_in = ch * ch_mult[self.num_resolutions - 1]
|
| 219 |
+
curr_res = resolution // 2 ** (self.num_resolutions - 1)
|
| 220 |
+
self.z_shape = (1, z_channels, curr_res, curr_res)
|
| 221 |
+
|
| 222 |
+
# z to block_in
|
| 223 |
+
self.conv_in = nn.Conv2d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
|
| 224 |
+
|
| 225 |
+
# middle
|
| 226 |
+
self.mid = nn.Module()
|
| 227 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)
|
| 228 |
+
self.mid.attn_1 = AttnBlock(block_in)
|
| 229 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)
|
| 230 |
+
|
| 231 |
+
# upsampling
|
| 232 |
+
self.up = nn.ModuleList()
|
| 233 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 234 |
+
block = nn.ModuleList()
|
| 235 |
+
attn = nn.ModuleList()
|
| 236 |
+
block_out = ch * ch_mult[i_level]
|
| 237 |
+
for _ in range(self.num_res_blocks + 1):
|
| 238 |
+
block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))
|
| 239 |
+
block_in = block_out
|
| 240 |
+
up = nn.Module()
|
| 241 |
+
up.block = block
|
| 242 |
+
up.attn = attn
|
| 243 |
+
if i_level != 0:
|
| 244 |
+
up.upsample = Upsample(block_in)
|
| 245 |
+
curr_res = curr_res * 2
|
| 246 |
+
self.up.insert(0, up) # prepend to get consistent order
|
| 247 |
+
|
| 248 |
+
# end
|
| 249 |
+
self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
|
| 250 |
+
self.conv_out = nn.Conv2d(block_in, out_ch, kernel_size=3, stride=1, padding=1)
|
| 251 |
+
|
| 252 |
+
def forward(self, z: Tensor) -> Tensor:
|
| 253 |
+
# z to block_in
|
| 254 |
+
h = self.conv_in(z)
|
| 255 |
+
|
| 256 |
+
# middle
|
| 257 |
+
h = self.mid.block_1(h)
|
| 258 |
+
h = self.mid.attn_1(h)
|
| 259 |
+
h = self.mid.block_2(h)
|
| 260 |
+
|
| 261 |
+
# upsampling
|
| 262 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 263 |
+
for i_block in range(self.num_res_blocks + 1):
|
| 264 |
+
h = self.up[i_level].block[i_block](h)
|
| 265 |
+
if len(self.up[i_level].attn) > 0:
|
| 266 |
+
h = self.up[i_level].attn[i_block](h)
|
| 267 |
+
if i_level != 0:
|
| 268 |
+
h = self.up[i_level].upsample(h)
|
| 269 |
+
|
| 270 |
+
# end
|
| 271 |
+
h = self.norm_out(h)
|
| 272 |
+
h = swish(h)
|
| 273 |
+
h = self.conv_out(h)
|
| 274 |
+
return h
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class DiagonalGaussian(nn.Module):
|
| 278 |
+
def __init__(self, sample: bool = True, chunk_dim: int = 1):
|
| 279 |
+
super().__init__()
|
| 280 |
+
self.sample = sample
|
| 281 |
+
self.chunk_dim = chunk_dim
|
| 282 |
+
|
| 283 |
+
def forward(self, z: Tensor) -> Tensor:
|
| 284 |
+
mean, logvar = torch.chunk(z, 2, dim=self.chunk_dim)
|
| 285 |
+
if self.sample:
|
| 286 |
+
std = torch.exp(0.5 * logvar)
|
| 287 |
+
return mean + std * torch.randn_like(mean)
|
| 288 |
+
else:
|
| 289 |
+
return mean
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class AutoEncoder(nn.Module):
|
| 293 |
+
def __init__(self, params: AutoEncoderParams):
|
| 294 |
+
super().__init__()
|
| 295 |
+
self.encoder = Encoder(
|
| 296 |
+
resolution=params.resolution,
|
| 297 |
+
in_channels=params.in_channels,
|
| 298 |
+
ch=params.ch,
|
| 299 |
+
ch_mult=params.ch_mult,
|
| 300 |
+
num_res_blocks=params.num_res_blocks,
|
| 301 |
+
z_channels=params.z_channels,
|
| 302 |
+
)
|
| 303 |
+
self.decoder = Decoder(
|
| 304 |
+
resolution=params.resolution,
|
| 305 |
+
in_channels=params.in_channels,
|
| 306 |
+
ch=params.ch,
|
| 307 |
+
out_ch=params.out_ch,
|
| 308 |
+
ch_mult=params.ch_mult,
|
| 309 |
+
num_res_blocks=params.num_res_blocks,
|
| 310 |
+
z_channels=params.z_channels,
|
| 311 |
+
)
|
| 312 |
+
self.reg = DiagonalGaussian()
|
| 313 |
+
|
| 314 |
+
self.scale_factor = params.scale_factor
|
| 315 |
+
self.shift_factor = params.shift_factor
|
| 316 |
+
|
| 317 |
+
def encode(self, x: Tensor) -> Tensor:
|
| 318 |
+
z = self.reg(self.encoder(x))
|
| 319 |
+
z = self.scale_factor * (z - self.shift_factor)
|
| 320 |
+
return z
|
| 321 |
+
|
| 322 |
+
def decode(self, z: Tensor) -> Tensor:
|
| 323 |
+
z = z / self.scale_factor + self.shift_factor
|
| 324 |
+
return self.decoder(z)
|
| 325 |
+
|
| 326 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 327 |
+
return self.decode(self.encode(x))
|