| 544 | |
| 545 | |
| 546 | class Decoder(nn.Module): |
| 547 | def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, |
| 548 | attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, |
| 549 | resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False, |
| 550 | attn_type="vanilla", **ignorekwargs): |
| 551 | super().__init__() |
| 552 | if use_linear_attn: attn_type = "linear" |
| 553 | self.ch = ch |
| 554 | self.temb_ch = 0 |
| 555 | self.num_resolutions = len(ch_mult) |
| 556 | self.num_res_blocks = num_res_blocks |
| 557 | self.resolution = resolution |
| 558 | self.in_channels = in_channels |
| 559 | self.give_pre_end = give_pre_end |
| 560 | self.tanh_out = tanh_out |
| 561 | |
| 562 | # compute in_ch_mult, block_in and curr_res at lowest res |
| 563 | in_ch_mult = (1,)+tuple(ch_mult) |
| 564 | block_in = ch*ch_mult[self.num_resolutions-1] |
| 565 | curr_res = resolution // 2**(self.num_resolutions-1) |
| 566 | self.z_shape = (1,z_channels,curr_res,curr_res) |
| 567 | print("Working with z of shape {} = {} dimensions.".format( |
| 568 | self.z_shape, np.prod(self.z_shape))) |
| 569 | |
| 570 | # z to block_in |
| 571 | self.conv_in = torch.nn.Conv2d(z_channels, |
| 572 | block_in, |
| 573 | kernel_size=3, |
| 574 | stride=1, |
| 575 | padding=1) |
| 576 | |
| 577 | # middle |
| 578 | self.mid = nn.Module() |
| 579 | self.mid.block_1 = ResnetBlock(in_channels=block_in, |
| 580 | out_channels=block_in, |
| 581 | temb_channels=self.temb_ch, |
| 582 | dropout=dropout) |
| 583 | self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) |
| 584 | self.mid.block_2 = ResnetBlock(in_channels=block_in, |
| 585 | out_channels=block_in, |
| 586 | temb_channels=self.temb_ch, |
| 587 | dropout=dropout) |
| 588 | |
| 589 | # upsampling |
| 590 | self.up = nn.ModuleList() |
| 591 | for i_level in reversed(range(self.num_resolutions)): |
| 592 | block = nn.ModuleList() |
| 593 | attn = nn.ModuleList() |
| 594 | block_out = ch*ch_mult[i_level] |
| 595 | for i_block in range(self.num_res_blocks+1): |
| 596 | block.append(ResnetBlock(in_channels=block_in, |
| 597 | out_channels=block_out, |
| 598 | temb_channels=self.temb_ch, |
| 599 | dropout=dropout)) |
| 600 | block_in = block_out |
| 601 | if curr_res in attn_resolutions: |
| 602 | attn.append(make_attn(block_in, attn_type=attn_type)) |
| 603 | up = nn.Module() |