| 157 | |
| 158 | |
| 159 | class Encoder(nn.Module): |
| 160 | def __init__(self, in_channels=3, ch=128, ch_mult=(1,1,2,2,4), num_res_blocks=2, |
| 161 | norm_type='group', dropout=0.0, resamp_with_conv=True, z_channels=256): |
| 162 | super().__init__() |
| 163 | self.num_resolutions = len(ch_mult) |
| 164 | self.num_res_blocks = num_res_blocks |
| 165 | self.conv_in = nn.Conv2d(in_channels, ch, kernel_size=3, stride=1, padding=1) |
| 166 | in_ch_mult = (1,) + tuple(ch_mult) |
| 167 | self.conv_blocks = nn.ModuleList() |
| 168 | for i_level in range(self.num_resolutions): |
| 169 | conv_block = nn.Module() |
| 170 | res_block = nn.ModuleList() |
| 171 | attn_block = nn.ModuleList() |
| 172 | block_in = ch*in_ch_mult[i_level] |
| 173 | block_out = ch*ch_mult[i_level] |
| 174 | for _ in range(self.num_res_blocks): |
| 175 | res_block.append(ResnetBlock(block_in, block_out, dropout=dropout, norm_type=norm_type)) |
| 176 | block_in = block_out |
| 177 | if i_level == self.num_resolutions - 1: |
| 178 | attn_block.append(AttnBlock(block_in, norm_type)) |
| 179 | conv_block.res = res_block |
| 180 | conv_block.attn = attn_block |
| 181 | if i_level != self.num_resolutions-1: |
| 182 | conv_block.downsample = Downsample(block_in, resamp_with_conv) |
| 183 | self.conv_blocks.append(conv_block) |
| 184 | self.mid = nn.ModuleList() |
| 185 | self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type)) |
| 186 | self.mid.append(AttnBlock(block_in, norm_type=norm_type)) |
| 187 | self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type)) |
| 188 | self.norm_out = Normalize(block_in, norm_type) |
| 189 | self.conv_out = nn.Conv2d(block_in, z_channels, kernel_size=3, stride=1, padding=1) |
| 190 | |
| 191 | def forward(self, x): |
| 192 | h = self.conv_in(x) |
| 193 | for i_level, block in enumerate(self.conv_blocks): |
| 194 | for i_block in range(self.num_res_blocks): |
| 195 | h = block.res[i_block](h) |
| 196 | if len(block.attn) > 0: |
| 197 | h = block.attn[i_block](h) |
| 198 | if i_level != self.num_resolutions - 1: |
| 199 | h = block.downsample(h) |
| 200 | for mid_block in self.mid: |
| 201 | h = mid_block(h) |
| 202 | h = self.norm_out(h) |
| 203 | h = nonlinearity(h) |
| 204 | h = self.conv_out(h) |
| 205 | return h |
| 206 | |
| 207 | class Decoder(nn.Module): |
| 208 | def __init__(self, z_channels=256, ch=128, ch_mult=(1,1,2,2,4), num_res_blocks=2, norm_type="group", |