| 108 | |
| 109 | |
| 110 | class ResnetBlock(nn.Module): |
| 111 | def __init__( |
| 112 | self, |
| 113 | *, |
| 114 | in_channels, |
| 115 | out_channels=None, |
| 116 | conv_shortcut=False, |
| 117 | dropout, |
| 118 | temb_channels=512, |
| 119 | zq_ch=None, |
| 120 | add_conv=False, |
| 121 | ): |
| 122 | super().__init__() |
| 123 | self.in_channels = in_channels |
| 124 | out_channels = in_channels if out_channels is None else out_channels |
| 125 | self.out_channels = out_channels |
| 126 | self.use_conv_shortcut = conv_shortcut |
| 127 | |
| 128 | self.norm1 = Normalize(in_channels, zq_ch, add_conv=add_conv) |
| 129 | self.conv1 = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) |
| 130 | if temb_channels > 0: |
| 131 | self.temb_proj = torch.nn.Linear(temb_channels, out_channels) |
| 132 | self.norm2 = Normalize(out_channels, zq_ch, add_conv=add_conv) |
| 133 | self.dropout = torch.nn.Dropout(dropout) |
| 134 | self.conv2 = torch.nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1) |
| 135 | if self.in_channels != self.out_channels: |
| 136 | if self.use_conv_shortcut: |
| 137 | self.conv_shortcut = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) |
| 138 | else: |
| 139 | self.nin_shortcut = torch.nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0) |
| 140 | |
| 141 | def forward(self, x, temb, zq): |
| 142 | h = x |
| 143 | h = self.norm1(h, zq) |
| 144 | h = nonlinearity(h) |
| 145 | h = self.conv1(h) |
| 146 | |
| 147 | if temb is not None: |
| 148 | h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None] |
| 149 | |
| 150 | h = self.norm2(h, zq) |
| 151 | h = nonlinearity(h) |
| 152 | h = self.dropout(h) |
| 153 | h = self.conv2(h) |
| 154 | |
| 155 | if self.in_channels != self.out_channels: |
| 156 | if self.use_conv_shortcut: |
| 157 | x = self.conv_shortcut(x) |
| 158 | else: |
| 159 | x = self.nin_shortcut(x) |
| 160 | |
| 161 | return x + h |
| 162 | |
| 163 | |
| 164 | class AttnBlock(nn.Module): |