File size: 5,789 Bytes
7328fd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import torch.nn as nn
import torch.nn.functional as F

class ChannelAttention(nn.Module):
    def __init__(self, in_planes, ratio=16):
        super(ChannelAttention, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.max_pool = nn.AdaptiveMaxPool2d(1)

        self.fc1 = nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False)
        self.relu1 = nn.ReLU()
        self.fc2 = nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False)

        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avg_out = self.fc2(self.relu1(self.fc1(self.avg_pool(x))))
        max_out = self.fc2(self.relu1(self.fc1(self.max_pool(x))))
        y = avg_out + max_out
        y = self.sigmoid(y)

        return x * y.expand_as(x)


class ResCell(nn.Module):
  def __init__(self, input_channel, output_channel, stride=1):
    super(ResCell, self).__init__()
    
    self.stride = stride
    self.input_channel = input_channel
    self.output_channel = output_channel

    if self.stride == -1:
      output_size = ()
      self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
      self.skip = nn.Conv2d(self.input_channel, self.output_channel, kernel_size=1, stride=1, padding=0)
      self.conv1 = nn.ConvTranspose2d(self.input_channel, self.output_channel, kernel_size=5, stride=2, padding=2, output_padding=1)
      self.conv2 = nn.ConvTranspose2d(self.output_channel, self.output_channel, kernel_size=5, padding=2)

    elif self.stride == 2:
      self.skip = nn.Conv2d(self.input_channel, self.output_channel, kernel_size=1, stride=2, padding=0)
      self.conv1 = nn.Conv2d(self.input_channel, self.output_channel, kernel_size=5, stride=self.stride, padding=2)
      self.conv2 = nn.Conv2d(self.output_channel, self.output_channel, kernel_size=5, padding=2)

    else:
      self.conv1 = nn.Conv2d(self.input_channel, self.output_channel, kernel_size=5, stride=self.stride, padding=2)
      self.conv2 = nn.Conv2d(self.output_channel, self.output_channel, kernel_size=5, padding=2)

    self.bn1 = nn.BatchNorm2d(self.output_channel)
    self.bn2 = nn.BatchNorm2d(self.output_channel)
    
    # Please replace `CBAM` with the actual module and parameters
    self.cbam = ChannelAttention(self.output_channel)

  def forward(self, x):
    if self.stride == -1:
      upsampled_x = self.upsample(x)
      skip = self.skip(upsampled_x)
      x = F.elu(self.bn1(self.conv1(x)))
      x = self.conv2(x)
    elif self.stride == 2:
      skip = self.skip(x)
      x = F.elu(self.bn1(self.conv1(x)))
      x = self.conv2(x)
    else:
      skip = x
      x = F.elu(self.bn1(self.conv1(x)))
      x = self.conv2(x)
    
    x = self.bn2(x)
    x = self.cbam(x)
    x = x + skip
    x = F.elu(x)

    return x


class ResBlock(nn.Module):
  def __init__(self, input_channel, output_channel, upsample=False, n_cells=2):
    super(ResBlock, self).__init__()

    stride = -1 if upsample else 2
    self.cells = nn.ModuleList([ResCell(input_channel, output_channel, stride=stride)])

    for _ in range(n_cells - 1):
        self.cells.append(ResCell(input_channel, output_channel, stride=1))

  def forward(self, x):
    for cell in self.cells:
        x = cell(x)
    return x


class Encoder(nn.Module):
  def __init__(self, input_shape, timbre_dim, N2=0, channel_sizes=None):
    super(Encoder, self).__init__()

    if channel_sizes is None:
        channel_sizes = [32, 64, 64, 96, 96, 128, 160, 216]
    
    self.input_shape = input_shape
    self.timbre_dim = timbre_dim
    self.blocks = nn.ModuleList()

    self.blocks.append(ResBlock(input_channel=1, output_channel=channel_sizes[0], upsample=False, n_cells=1))
    input_channel = channel_sizes[0]

    for c in channel_sizes[1:]:
        self.blocks.append(ResBlock(input_channel=input_channel, output_channel=c, upsample=False, n_cells=1 + N2))
        input_channel = c

    self.flatten = nn.Flatten()
    self.mu_timbre = nn.Linear(self._get_flattened_dim(), timbre_dim)
    self.sigma_timbre = nn.Linear(self._get_flattened_dim(), timbre_dim)

  def _get_flattened_dim(self):
    x = torch.zeros((1,) + self.input_shape)
    for block in self.blocks:
        x = block(x)
    x = self.flatten(x)
    return x.shape[1]

  def reparameterize(self, mu, logvar):
    std = torch.exp(0.5*logvar)
    eps = torch.randn_like(std)
    return mu + eps*std

  def forward(self, x):
    for block in self.blocks:
        x = block(x)

    x = self.flatten(x)
    mu = self.mu_timbre(x)
    logvar = self.sigma_timbre(x)
    latent_vector = self.reparameterize(mu, logvar)
    
#     kl_loss = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp(), dim=1)
#     kl_loss = torch.mean(kl_loss)
    
    return mu, logvar, latent_vector


class Decoder(nn.Module):
  def __init__(self, timbre_dim, N2=0, N3=8, channel_sizes=None):
    super(Decoder, self).__init__()

    if channel_sizes is None:
        channel_sizes = [32, 64, 64, 96, 96, 128, 160, 216]

    self.conv_shape = [-1, channel_sizes[-1], 2 ** (9 - N3), 2 ** (8 - N3)]

    self.dense = nn.Linear(timbre_dim, self.conv_shape[1] * self.conv_shape[2] * self.conv_shape[3])
    self.blocks = nn.ModuleList()

    input_channel = channel_sizes[-1]
    for c in list(reversed(channel_sizes))[1:]:
        self.blocks.append(ResBlock(input_channel=input_channel, output_channel=c, upsample=True, n_cells=1 + N2))
        input_channel = c

    self.decoder_conv = nn.ConvTranspose2d(channel_sizes[0], 1, kernel_size=5, stride=2, padding=2, output_padding=1)

  def forward(self, x):
    x = F.elu(self.dense(x))
    x = x.view(-1, self.conv_shape[1], self.conv_shape[2], self.conv_shape[3])
    for block in self.blocks:
        x = block(x)
    
    x = self.decoder_conv(x)
    x = torch.sigmoid(x)
    return x