| 460 | |
| 461 | |
| 462 | class Decoder(nn.Module): |
| 463 | def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, |
| 464 | attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, |
| 465 | resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False, |
| 466 | attn_type="vanilla", **ignorekwargs): |
| 467 | super().__init__() |
| 468 | if use_linear_attn: attn_type = "linear" |
| 469 | self.ch = ch |
| 470 | self.temb_ch = 0 |
| 471 | self.num_resolutions = len(ch_mult) |
| 472 | self.num_res_blocks = num_res_blocks |
| 473 | self.resolution = resolution |
| 474 | self.in_channels = in_channels |
| 475 | self.give_pre_end = give_pre_end |
| 476 | self.tanh_out = tanh_out |
| 477 | |
| 478 | # compute in_ch_mult, block_in and curr_res at lowest res |
| 479 | in_ch_mult = (1,)+tuple(ch_mult) |
| 480 | block_in = ch*ch_mult[self.num_resolutions-1] |
| 481 | curr_res = resolution // 2**(self.num_resolutions-1) |
| 482 | self.z_shape = (1,z_channels,curr_res,curr_res) |
| 483 | print("Working with z of shape {} = {} dimensions.".format( |
| 484 | self.z_shape, np.prod(self.z_shape))) |
| 485 | |
| 486 | # z to block_in |
| 487 | self.conv_in = torch.nn.Conv2d(z_channels, |
| 488 | block_in, |
| 489 | kernel_size=3, |
| 490 | stride=1, |
| 491 | padding=1) |
| 492 | |
| 493 | # middle |
| 494 | self.mid = nn.Module() |
| 495 | self.mid.block_1 = ResnetBlock(in_channels=block_in, |
| 496 | out_channels=block_in, |
| 497 | temb_channels=self.temb_ch, |
| 498 | dropout=dropout) |
| 499 | self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) |
| 500 | self.mid.block_2 = ResnetBlock(in_channels=block_in, |
| 501 | out_channels=block_in, |
| 502 | temb_channels=self.temb_ch, |
| 503 | dropout=dropout) |
| 504 | |
| 505 | # upsampling |
| 506 | self.up = nn.ModuleList() |
| 507 | for i_level in reversed(range(self.num_resolutions)): |
| 508 | block = nn.ModuleList() |
| 509 | attn = nn.ModuleList() |
| 510 | block_out = ch*ch_mult[i_level] |
| 511 | for i_block in range(self.num_res_blocks+1): |
| 512 | block.append(ResnetBlock(in_channels=block_in, |
| 513 | out_channels=block_out, |
| 514 | temb_channels=self.temb_ch, |
| 515 | dropout=dropout)) |
| 516 | block_in = block_out |
| 517 | if curr_res in attn_resolutions: |
| 518 | attn.append(make_attn(block_in, attn_type=attn_type)) |
| 519 | up = nn.Module() |