| 457 | |
| 458 | |
| 459 | class Encoder(nn.Module): |
| 460 | def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, |
| 461 | attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, |
| 462 | resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla", |
| 463 | **ignore_kwargs): |
| 464 | super().__init__() |
| 465 | if use_linear_attn: attn_type = "linear" |
| 466 | self.ch = ch |
| 467 | self.temb_ch = 0 |
| 468 | self.num_resolutions = len(ch_mult) |
| 469 | self.num_res_blocks = num_res_blocks |
| 470 | self.resolution = resolution |
| 471 | self.in_channels = in_channels |
| 472 | |
| 473 | # downsampling |
| 474 | self.conv_in = torch.nn.Conv2d(in_channels, |
| 475 | self.ch, |
| 476 | kernel_size=3, |
| 477 | stride=1, |
| 478 | padding=1) |
| 479 | |
| 480 | |
| 481 | curr_res = resolution |
| 482 | in_ch_mult = (1,)+tuple(ch_mult) |
| 483 | self.in_ch_mult = in_ch_mult |
| 484 | self.down = nn.ModuleList() |
| 485 | for i_level in range(self.num_resolutions): |
| 486 | block = nn.ModuleList() |
| 487 | attn = nn.ModuleList() |
| 488 | block_in = ch*in_ch_mult[i_level] |
| 489 | block_out = ch*ch_mult[i_level] |
| 490 | for i_block in range(self.num_res_blocks): |
| 491 | block.append(ResnetBlock(in_channels=block_in, |
| 492 | out_channels=block_out, |
| 493 | temb_channels=self.temb_ch, |
| 494 | dropout=dropout)) |
| 495 | block_in = block_out |
| 496 | if curr_res in attn_resolutions: |
| 497 | attn.append(make_attn(block_in, attn_type=attn_type)) |
| 498 | down = nn.Module() |
| 499 | down.block = block |
| 500 | down.attn = attn |
| 501 | if i_level != self.num_resolutions-1: |
| 502 | down.downsample = Downsample(block_in, resamp_with_conv) |
| 503 | curr_res = curr_res // 2 |
| 504 | self.down.append(down) |
| 505 | |
| 506 | # middle |
| 507 | self.mid = nn.Module() |
| 508 | self.mid.block_1 = ResnetBlock(in_channels=block_in, |
| 509 | out_channels=block_in, |
| 510 | temb_channels=self.temb_ch, |
| 511 | dropout=dropout) |
| 512 | self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) |
| 513 | self.mid.block_2 = ResnetBlock(in_channels=block_in, |
| 514 | out_channels=block_in, |
| 515 | temb_channels=self.temb_ch, |
| 516 | dropout=dropout) |