1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
| import torch import torch.nn as nn import torch.nn.functional as F
import yaml
with open('options.yml', 'r') as f: opt = yaml.safe_load(f) img_shape = opt['dataset']['img_shape'][opt['dataset']['name']]
class PositionalEncoding(nn.Module): def __init__(self, max_seq_len: int, d_model: int, n_classes: int=None): super().__init__()
assert d_model % 2 == 0
pe = torch.zeros(max_seq_len, d_model) i_seq = torch.linspace(0, max_seq_len - 1, max_seq_len) j_seq = torch.linspace(0, d_model - 2, d_model // 2) pos, two_i = torch.meshgrid(i_seq, j_seq) pe_2i = torch.sin(pos / 1e4 ** (two_i / d_model)) pe_2i_1 = torch.cos(pos / 1e4 ** (two_i / d_model)) pe = torch.stack((pe_2i, pe_2i_1), 2).reshape(max_seq_len, d_model)
self.t_embedding = nn.Embedding(max_seq_len, d_model) self.t_embedding.weight.data = pe self.t_embedding.requires_grad_(False)
self.use_condition = n_classes is not None if self.use_condition: self.label_embedding = nn.Embedding(n_classes, d_model) def forward(self, t, label=None): t_emb = self.t_embedding(t) if self.use_condition and label is not None: label_emb = self.label_embedding(label) return t_emb + label_emb return t_emb
class SelfAttention(nn.Module): def __init__(self, channels: int, num_heads: int): super().__init__() self.channels = channels self.mha = nn.MultiheadAttention(channels, num_heads, batch_first=True) self.ln = nn.LayerNorm([channels]) self.ff_self = nn.Sequential( nn.LayerNorm([channels]), nn.Linear(channels, channels), nn.GELU(), nn.Linear(channels, channels), ) def forward(self, x: torch.Tensor): size = x.shape[-2:] x = x.view(x.shape[0], self.channels, -1).transpose(1, 2) x_ln = self.ln(x) attention_value, _ = self.mha(x_ln, x_ln, x_ln) attention_value = attention_value + x attention_value = self.ff_self(attention_value) + attention_value return attention_value.transpose(1, 2).view(x.shape[0], self.channels, *size)
class UNetBlock(nn.Module): def __init__(self, shape, in_c, out_c, residual=False): super().__init__() self.ln = nn.LayerNorm(shape) self.conv1 = nn.Conv2d(in_c, out_c, kernel_size=3, stride=1, padding=1) self.conv2 = nn.Conv2d(out_c, out_c, kernel_size=3, stride=1, padding=1) self.activation = nn.ReLU() self.residual = residual if residual: if in_c == out_c: self.residual_conv = nn.Identity() else: self.residual_conv = nn.Conv2d(in_c, out_c, kernel_size=1) def forward(self, x): out = self.activation(self.conv1(self.ln(x))) out = self.conv2(out) if self.residual: out += self.residual_conv(x) out = self.activation(out) return out
class UNet(nn.Module): def __init__(self, n_steps: int, channels: list=[10, 20, 40, 80], pe_dim: int=10, residual: bool=False, n_classes: int=10, use_attention: bool = True): super().__init__() C, H, W = img_shape[0], img_shape[1], img_shape[2] n_layers = len(channels) Hs = [H] Ws = [W] cH = H cW = W for _ in range(n_layers - 1): cH //= 2 cW //= 2 Hs.append(cH) Ws.append(cW) self.pe = PositionalEncoding(n_steps, pe_dim, n_classes) self.encoders = nn.ModuleList() self.decoders = nn.ModuleList() self.pe_linears_en = nn.ModuleList() self.pe_linears_de = nn.ModuleList() self.downs = nn.ModuleList() self.ups = nn.ModuleList() prev_channel = C
for channel, cH, cW in zip(channels[0:-1], Hs[0:-1], Ws[0:-1]): self.pe_linears_en.append( nn.Sequential(nn.Linear(pe_dim, prev_channel), nn.ReLU(), nn.Linear(prev_channel, prev_channel)) ) self.encoders.append( nn.Sequential( UNetBlock((prev_channel, cH, cW), prev_channel, channel, residual=residual), UNetBlock((channel, cH, cW), channel, channel, residual=residual) ) ) self.downs.append(nn.Conv2d(channel, channel, kernel_size=2, stride=2)) prev_channel = channel self.pe_mid = nn.Linear(pe_dim, prev_channel) channel = channels[-1] if not use_attention: self.mid = nn.Sequential( UNetBlock((prev_channel, Hs[-1], Ws[-1]), prev_channel, channel, residual=residual), UNetBlock((channel, Hs[-1], Ws[-1]), channel, channel, residual=residual) ) else: self.mid = nn.Sequential( UNetBlock((prev_channel, Hs[-1], Ws[-1]), prev_channel, channel, residual=residual), SelfAttention(channel, 4), UNetBlock((channel, Hs[-1], Ws[-1]), channel, channel, residual=residual) ) prev_channel = channel
for channel, cH, cW in zip(channels[-2::-1], Hs[-2::-1], Ws[-2::-1]): self.pe_linears_de.append(nn.Linear(pe_dim, prev_channel)) self.decoders.append( nn.Sequential( UNetBlock((channel * 2, cH, cW), channel * 2, channel, residual=residual), UNetBlock((channel, cH, cW), channel, channel, residual=residual) ) ) self.ups.append(nn.ConvTranspose2d(prev_channel, channel, kernel_size=2, stride=2)) prev_channel = channel self.conv_out = nn.Conv2d(prev_channel, C, kernel_size=3, stride=1, padding=1) def forward(self, x, t, label=None): n = t.shape[0] t = self.pe(t, label) encoder_outs = [] for pe_linear, encoder, down in zip(self.pe_linears_en, self.encoders, self.downs): pe = pe_linear(t).reshape(n, -1, 1, 1) x = encoder(x + pe) encoder_outs.append(x) x = down(x) pe = self.pe_mid(t).reshape(n, -1, 1, 1) x = self.mid(x + pe) for pe_linear, decoder, up, encoder_out in zip(self.pe_linears_de, self.decoders, self.ups, encoder_outs[::-1]): pe = pe_linear(t).reshape(n, -1, 1, 1) x = up(x) pad_x = encoder_out.shape[2] - x.shape[2] pad_y = encoder_out.shape[3] - x.shape[3] x = F.pad(x, (pad_x // 2, pad_x - pad_x//2, pad_y // 2, pad_y - pad_y//2)) x = torch.cat((encoder_out, x), dim=1) x = decoder(x + pe) x = self.conv_out(x) return x
def build_network(n_steps: int, channels: list, pe_dim: bool=None, residual: bool=True, n_classes: int=10, use_attention: bool=True): return UNet(n_steps, channels, pe_dim, residual, n_classes, use_attention)
|