pooling.py 6.59 KB
Newer Older
Anthony Larcher's avatar
Anthony Larcher committed
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
# coding: utf-8 -*-
#
# This file is part of SIDEKIT.
#
# SIDEKIT is a python package for speaker verification.
# Home page: http://www-lium.univ-lemans.fr/sidekit/
#
# SIDEKIT is a python package for speaker verification.
# Home page: http://www-lium.univ-lemans.fr/sidekit/
#
# SIDEKIT is free software: you can redistribute it and/or modify
# it under the terms of the GNU LLesser General Public License as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# SIDEKIT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with SIDEKIT.  If not, see <http://www.gnu.org/licenses/>.

"""
Copyright 2014-2021 Anthony Larcher, Yevhenii Prokopalo
"""


import os
import torch


os.environ['MKL_THREADING_LAYER'] = 'GNU'

__license__ = "LGPL"
__author__ = "Anthony Larcher"
__copyright__ = "Copyright 2015-2021 Anthony Larcher"
__maintainer__ = "Anthony Larcher"
__email__ = "anthony.larcher@univ-lemans.fr"
__status__ = "Production"
__docformat__ = 'reS'


class MeanStdPooling(torch.nn.Module):
    """
    Mean and Standard deviation pooling
    """
    def __init__(self):
        """

        """
        super(MeanStdPooling, self).__init__()
        pass

    def forward(self, x):
        """

Le Lan Gaël's avatar
speedup    
Le Lan Gaël committed
58
        :param x: [B, C*F, T]
Anthony Larcher's avatar
Anthony Larcher committed
59
60
        :return:
        """
Le Lan Gaël's avatar
speedup    
Le Lan Gaël committed
61
62
63
64
65
        if len(x.shape) == 4:
            # [B, C, F, T]
            x = x.permute(0, 1, 3, 2)
            x = x.flatten(start_dim=1, end_dim=2)
        # [B, C*F]
Anthony Larcher's avatar
Anthony Larcher committed
66
        mean = torch.mean(x, dim=2)
Le Lan Gaël's avatar
speedup    
Le Lan Gaël committed
67
        # [B, C*F]
Anthony Larcher's avatar
Anthony Larcher committed
68
        std = torch.std(x, dim=2)
Le Lan Gaël's avatar
speedup    
Le Lan Gaël committed
69
        # [B, 2*C*F]
Anthony Larcher's avatar
Anthony Larcher committed
70
71
72
        return torch.cat([mean, std], dim=1)


73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class ChannelWiseCorrPooling(torch.nn.Module):
    def __init__(self, in_channels=256, out_channels=64, in_freqs=10, channels_dropout=0.25):
        super(ChannelWiseCorrPooling, self).__init__()
        self.channels_dropout = channels_dropout
        self.merge_freqs_count = 2
        assert in_freqs % self.merge_freqs_count == 0
        self.groups = in_freqs//self.merge_freqs_count
        self.out_channels = out_channels
        self.out_dim = int(self.out_channels*(self.out_channels-1)/2)*self.groups
        self.L_proj = torch.nn.Conv2d(in_channels*self.groups, out_channels*self.groups, kernel_size=(1, 1), groups=self.groups)
        #self.L_proj = torch.nn.Conv2d(in_channels, out_channels, kernel_size=(1, 1))
        self.mask = torch.tril(torch.ones((out_channels, out_channels)), diagonal=-1).type(torch.BoolTensor)

    def forward(self, x):
        """

        :param x: [B, C, T, F]
        :return:
        """
        batch_size=x.shape[0]
        num_locations = x.shape[-1]*x.shape[-2]/self.groups
        self.mask = self.mask.to(x.device)
        if self.training:
            x *= torch.nn.functional.dropout(torch.ones((1, x.shape[1], 1, 1), device=x.device), p=self.channels_dropout)
Le Lan Gaël's avatar
Le Lan Gaël committed
97
98
99
100
101
102
103
104
105
106
107
        #[B, T, C, F]
        x = x.permute(0, 2, 1, 3)
        #[B, T, C, Fr, f]
        x = x.reshape(x.shape[0], x.shape[1], x.shape[-2], self.groups, self.merge_freqs_count)
        #[B, T, f, Fr, C]
        x = x.permute(0, 1, 4, 3, 2)
        #[B, T, f, Fr*C]
        x = x.flatten(start_dim=3, end_dim=4)
        #[B, Fr*C, T, f]
        x = x.permute(0, 3, 1, 2)
        #[B, Fr*C', T, f]
108
109
        x = self.L_proj(x)
        #[B, Fr, C', Tr]
Le Lan Gaël's avatar
Le Lan Gaël committed
110
        x = x.reshape(x.shape[0], self.groups, self.out_channels, -1)
111
112
113
114
115
116
117
118
119
        x -= torch.mean(x, axis=-1, keepdims=True)
        out = x/(torch.std(x, axis=-1, keepdims=True) + 1e-5)
        #[B, C', C']
        out = torch.einsum('abci,abdi->abcd', out, out)
        #[B, C'*(C'-1)/2]
        out = torch.masked_select(out, self.mask).reshape(batch_size, -1)
        out = out/num_locations
        return out

Anthony Larcher's avatar
Anthony Larcher committed
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
class AttentivePooling(torch.nn.Module):
    """
    Mean and Standard deviation attentive pooling
    """
    def __init__(self, num_channels, n_mels, reduction=2, global_context=False):
        """

        """
        # TODO Make global_context configurable (True/False)
        # TODO Make convolution parameters configurable
        super(AttentivePooling, self).__init__()
        in_factor = 3 if global_context else 1
        self.attention = torch.nn.Sequential(
            torch.nn.Conv1d(num_channels * (n_mels//8) * in_factor, num_channels//reduction, kernel_size=1),
            torch.nn.ReLU(),
            torch.nn.BatchNorm1d(num_channels//reduction),
            torch.nn.Tanh(),
            torch.nn.Conv1d(num_channels//reduction, num_channels * (n_mels//8), kernel_size=1),
            torch.nn.Softmax(dim=2),
        )
        self.global_context = global_context
        self.gc = MeanStdPooling()

    def new_parameter(self, *size):
        out = torch.nn.Parameter(torch.FloatTensor(*size))
        torch.nn.init.xavier_normal_(out)
        return out

    def forward(self, x):
        """

Le Lan Gaël's avatar
speedup    
Le Lan Gaël committed
151
        :param x: [B, C*F, T]
Anthony Larcher's avatar
Anthony Larcher committed
152
153
        :return:
        """
Le Lan Gaël's avatar
speedup    
Le Lan Gaël committed
154
155
156
157
158
        if len(x.shape) == 4:
            # [B, C, F, T]
            x = x.permute(0, 1, 3, 2)
            # [B, C*F, T]
            x = x.flatten(start_dim=1, end_dim=2)
Anthony Larcher's avatar
Anthony Larcher committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        if self.global_context:
            w = self.attention(torch.cat([x, self.gc(x).unsqueeze(2).repeat(1, 1, x.shape[-1])], dim=1))
        else:
            w = self.attention(x)

        mu = torch.sum(x * w, dim=2)
        rh = torch.sqrt( ( torch.sum((x**2) * w, dim=2) - mu**2 ).clamp(min=1e-5) )
        x = torch.cat((mu, rh),1)
        x = x.view(x.size()[0], -1)
        return x


class GruPooling(torch.nn.Module):
    """
Anthony Larcher's avatar
Anthony Larcher committed
173
    Pooling done by using a recurrent network
Anthony Larcher's avatar
Anthony Larcher committed
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
    """
    def __init__(self, input_size, gru_node, nb_gru_layer):
        """

        :param input_size:
        :param gru_node:
        :param nb_gru_layer:
        """
        super(GruPooling, self).__init__()
        self.lrelu_keras = torch.nn.LeakyReLU(negative_slope = 0.3)
        self.bn_before_gru = torch.nn.BatchNorm1d(num_features = input_size)
        self.gru = torch.nn.GRU(input_size = input_size,
                                hidden_size = gru_node,
                                num_layers = nb_gru_layer,
                                batch_first = True)

    def forward(self, x):
        """

        :param x:
        :return:
        """
        x = self.bn_before_gru(x)
        x = self.lrelu_keras(x)
Anthony Larcher's avatar
Anthony Larcher committed
198
        x = x.permute(0, 2, 1)  # (batch, filt, time) >> (batch, time, filt)
Anthony Larcher's avatar
Anthony Larcher committed
199
200
201
202
203
        self.gru.flatten_parameters()
        x, _ = self.gru(x)
        x = x[:, -1, :]

        return x