| 429 | |
| 430 | |
| 431 | class Encoder(nn.Module): |
| 432 | def __init__( |
| 433 | self, |
| 434 | *, |
| 435 | ch, |
| 436 | out_ch, |
| 437 | ch_mult=(1, 2, 4, 8), |
| 438 | num_res_blocks, |
| 439 | attn_resolutions, |
| 440 | dropout=0.0, |
| 441 | resamp_with_conv=True, |
| 442 | in_channels, |
| 443 | resolution, |
| 444 | z_channels, |
| 445 | double_z=True, |
| 446 | use_linear_attn=False, |
| 447 | attn_type="vanilla", |
| 448 | **ignore_kwargs, |
| 449 | ): |
| 450 | super().__init__() |
| 451 | if use_linear_attn: |
| 452 | attn_type = "linear" |
| 453 | self.ch = ch |
| 454 | self.temb_ch = 0 |
| 455 | self.num_resolutions = len(ch_mult) |
| 456 | self.num_res_blocks = num_res_blocks |
| 457 | self.resolution = resolution |
| 458 | self.in_channels = in_channels |
| 459 | |
| 460 | # downsampling |
| 461 | self.conv_in = torch.nn.Conv2d( |
| 462 | in_channels, self.ch, kernel_size=3, stride=1, padding=1 |
| 463 | ) |
| 464 | |
| 465 | curr_res = resolution |
| 466 | in_ch_mult = (1,) + tuple(ch_mult) |
| 467 | self.in_ch_mult = in_ch_mult |
| 468 | self.down = nn.ModuleList() |
| 469 | for i_level in range(self.num_resolutions): |
| 470 | block = nn.ModuleList() |
| 471 | attn = nn.ModuleList() |
| 472 | block_in = ch * in_ch_mult[i_level] |
| 473 | block_out = ch * ch_mult[i_level] |
| 474 | for i_block in range(self.num_res_blocks): |
| 475 | block.append( |
| 476 | ResnetBlock( |
| 477 | in_channels=block_in, |
| 478 | out_channels=block_out, |
| 479 | temb_channels=self.temb_ch, |
| 480 | dropout=dropout, |
| 481 | ) |
| 482 | ) |
| 483 | block_in = block_out |
| 484 | if curr_res in attn_resolutions: |
| 485 | attn.append(make_attn(block_in, attn_type=attn_type)) |
| 486 | down = nn.Module() |
| 487 | down.block = block |
| 488 | down.attn = attn |