Welcome to mirror list, hosted at ThFree Co, Russian Federation.

lace_loss_metric.py « evaluation « stndrd « osce « torch « dnn - gitlab.xiph.org/xiph/opus.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b0790585b3cb615bea4ff420dabafb99c2616a80 (plain)
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""
/* Copyright (c) 2023 Amazon
   Written by Jan Buethe */
/*
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

   - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
   OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"""

"""STFT-based Loss modules."""

import torch
import torch.nn.functional as F
from torch import nn
import numpy as np
import torchaudio


def get_window(win_name, win_length, *args, **kwargs):
    window_dict = {
        'bartlett_window'   : torch.bartlett_window,
        'blackman_window'   : torch.blackman_window,
        'hamming_window'    : torch.hamming_window,
        'hann_window'       : torch.hann_window,
        'kaiser_window'     : torch.kaiser_window
    }

    if not win_name in window_dict:
        raise ValueError()

    return window_dict[win_name](win_length, *args, **kwargs)


def stft(x, fft_size, hop_size, win_length, window):
    """Perform STFT and convert to magnitude spectrogram.
    Args:
        x (Tensor): Input signal tensor (B, T).
        fft_size (int): FFT size.
        hop_size (int): Hop size.
        win_length (int): Window length.
        window (str): Window function type.
    Returns:
        Tensor: Magnitude spectrogram (B, #frames, fft_size // 2 + 1).
    """

    win = get_window(window, win_length).to(x.device)
    x_stft = torch.stft(x, fft_size, hop_size, win_length, win, return_complex=True)


    return torch.clamp(torch.abs(x_stft), min=1e-7)

def spectral_convergence_loss(Y_true, Y_pred):
    dims=list(range(1, len(Y_pred.shape)))
    return torch.mean(torch.norm(torch.abs(Y_true) - torch.abs(Y_pred), p="fro", dim=dims) / (torch.norm(Y_pred, p="fro", dim=dims) + 1e-6))


def log_magnitude_loss(Y_true, Y_pred):
    Y_true_log_abs = torch.log(torch.abs(Y_true) + 1e-15)
    Y_pred_log_abs = torch.log(torch.abs(Y_pred) + 1e-15)

    return torch.mean(torch.abs(Y_true_log_abs - Y_pred_log_abs))

def spectral_xcorr_loss(Y_true, Y_pred):
    Y_true = Y_true.abs()
    Y_pred = Y_pred.abs()
    dims=list(range(1, len(Y_pred.shape)))
    xcorr = torch.sum(Y_true * Y_pred, dim=dims) / torch.sqrt(torch.sum(Y_true ** 2, dim=dims) * torch.sum(Y_pred ** 2, dim=dims) + 1e-9)

    return 1 - xcorr.mean()



class MRLogMelLoss(nn.Module):
    def __init__(self,
                 fft_sizes=[512, 256, 128, 64],
                 overlap=0.5,
                 fs=16000,
                 n_mels=18
                 ):

        self.fft_sizes  = fft_sizes
        self.overlap    = overlap
        self.fs         = fs
        self.n_mels     = n_mels

        super().__init__()

        self.mel_specs = []
        for fft_size in fft_sizes:
            hop_size = int(round(fft_size * (1 - self.overlap)))

            n_mels = self.n_mels
            if fft_size < 128:
                n_mels //= 2

            self.mel_specs.append(torchaudio.transforms.MelSpectrogram(fs, fft_size, hop_length=hop_size, n_mels=n_mels))

        for i, mel_spec in enumerate(self.mel_specs):
            self.add_module(f'mel_spec_{i+1}', mel_spec)

    def forward(self, y_true, y_pred):

        loss = torch.zeros(1, device=y_true.device)

        for mel_spec in self.mel_specs:
            Y_true = mel_spec(y_true)
            Y_pred = mel_spec(y_pred)
            loss = loss + log_magnitude_loss(Y_true, Y_pred)

        loss = loss / len(self.mel_specs)

        return loss

def create_weight_matrix(num_bins, bins_per_band=10):
    m = torch.zeros((num_bins, num_bins), dtype=torch.float32)

    r0 = bins_per_band // 2
    r1 = bins_per_band - r0

    for i in range(num_bins):
        i0 = max(i - r0, 0)
        j0 = min(i + r1, num_bins)

        m[i, i0: j0] += 1

        if i < r0:
            m[i, :r0 - i] += 1

        if i > num_bins - r1:
            m[i, num_bins - r1 - i:] += 1

    return m / bins_per_band

def weighted_spectral_convergence(Y_true, Y_pred, w):

    # calculate sfm based weights
    logY = torch.log(torch.abs(Y_true) + 1e-9)
    Y = torch.abs(Y_true)

    avg_logY = torch.matmul(logY.transpose(1, 2), w)
    avg_Y = torch.matmul(Y.transpose(1, 2), w)

    sfm = torch.exp(avg_logY) / (avg_Y + 1e-9)

    weight = (torch.relu(1 - sfm) ** .5).transpose(1, 2)

    loss = torch.mean(
        torch.mean(weight * torch.abs(torch.abs(Y_true) - torch.abs(Y_pred)), dim=[1, 2])
        / (torch.mean( weight * torch.abs(Y_true), dim=[1, 2]) + 1e-9)
    )

    return loss

def gen_filterbank(N, Fs=16000):
    in_freq = (np.arange(N+1, dtype='float32')/N*Fs/2)[None,:]
    out_freq = (np.arange(N, dtype='float32')/N*Fs/2)[:,None]
    #ERB from B.C.J Moore, An Introduction to the Psychology of Hearing, 5th Ed., page 73.
    ERB_N = 24.7 + .108*in_freq
    delta = np.abs(in_freq-out_freq)/ERB_N
    center = (delta<.5).astype('float32')
    R = -12*center*delta**2 + (1-center)*(3-12*delta)
    RE = 10.**(R/10.)
    norm = np.sum(RE, axis=1)
    RE = RE/norm[:, np.newaxis]
    return torch.from_numpy(RE)

def smooth_log_mag(Y_true, Y_pred, filterbank):
    Y_true_smooth = torch.matmul(filterbank, torch.abs(Y_true))
    Y_pred_smooth = torch.matmul(filterbank, torch.abs(Y_pred))

    loss = torch.abs(
        torch.log(Y_true_smooth + 1e-9) - torch.log(Y_pred_smooth + 1e-9)
    )

    loss = loss.mean()

    return loss

class MRSTFTLoss(nn.Module):
    def __init__(self,
                 fft_sizes=[2048, 1024, 512, 256, 128, 64],
                 overlap=0.5,
                 window='hann_window',
                 fs=16000,
                 log_mag_weight=0,
                 sc_weight=0,
                 wsc_weight=0,
                 smooth_log_mag_weight=2,
                 sxcorr_weight=1):
        super().__init__()

        self.fft_sizes = fft_sizes
        self.overlap = overlap
        self.window = window
        self.log_mag_weight = log_mag_weight
        self.sc_weight = sc_weight
        self.wsc_weight = wsc_weight
        self.smooth_log_mag_weight = smooth_log_mag_weight
        self.sxcorr_weight = sxcorr_weight
        self.fs = fs

        # weights for SFM weighted spectral convergence loss
        self.wsc_weights = torch.nn.ParameterDict()
        for fft_size in fft_sizes:
            width = min(11, int(1000 * fft_size / self.fs + .5))
            width += width % 2
            self.wsc_weights[str(fft_size)] = torch.nn.Parameter(
                create_weight_matrix(fft_size // 2 + 1, width),
                requires_grad=False
            )

        # filterbanks for smooth log magnitude loss
        self.filterbanks = torch.nn.ParameterDict()
        for fft_size in fft_sizes:
            self.filterbanks[str(fft_size)] = torch.nn.Parameter(
                gen_filterbank(fft_size//2),
                requires_grad=False
            )


    def __call__(self, y_true, y_pred):


        lm_loss = torch.zeros(1, device=y_true.device)
        sc_loss = torch.zeros(1, device=y_true.device)
        wsc_loss = torch.zeros(1, device=y_true.device)
        slm_loss = torch.zeros(1, device=y_true.device)
        sxcorr_loss = torch.zeros(1, device=y_true.device)

        for fft_size in self.fft_sizes:
            hop_size = int(round(fft_size * (1 - self.overlap)))
            win_size = fft_size

            Y_true = stft(y_true, fft_size, hop_size, win_size, self.window)
            Y_pred = stft(y_pred, fft_size, hop_size, win_size, self.window)

            if self.log_mag_weight > 0:
                lm_loss = lm_loss + log_magnitude_loss(Y_true, Y_pred)

            if self.sc_weight > 0:
                sc_loss = sc_loss + spectral_convergence_loss(Y_true, Y_pred)

            if self.wsc_weight > 0:
                wsc_loss = wsc_loss + weighted_spectral_convergence(Y_true, Y_pred, self.wsc_weights[str(fft_size)])

            if self.smooth_log_mag_weight > 0:
                slm_loss = slm_loss + smooth_log_mag(Y_true, Y_pred, self.filterbanks[str(fft_size)])

            if self.sxcorr_weight > 0:
                sxcorr_loss = sxcorr_loss + spectral_xcorr_loss(Y_true, Y_pred)


        total_loss = (self.log_mag_weight * lm_loss + self.sc_weight * sc_loss
                + self.wsc_weight * wsc_loss + self.smooth_log_mag_weight * slm_loss
                + self.sxcorr_weight * sxcorr_loss) / len(self.fft_sizes)

        return total_loss


def td_l2_norm(y_true, y_pred):
    dims = list(range(1, len(y_true.shape)))

    loss = torch.mean((y_true - y_pred) ** 2, dim=dims) / (torch.mean(y_pred ** 2, dim=dims) ** .5 + 1e-6)

    return loss.mean()


class LaceLoss(nn.Module):
    def __init__(self):
        super().__init__()


        self.stftloss = MRSTFTLoss(log_mag_weight=0, sc_weight=0, wsc_weight=0, smooth_log_mag_weight=2, sxcorr_weight=1)


    def forward(self, x, y):
        specloss = self.stftloss(x, y)
        phaseloss = td_l2_norm(x, y)
        total_loss = (specloss + 10 * phaseloss) / 13

        return total_loss

    def compare(self, x_ref, x_deg):
        # trim items to same size
        n = min(len(x_ref), len(x_deg))
        x_ref = x_ref[:n].copy()
        x_deg = x_deg[:n].copy()

        # pre-emphasis
        x_ref[1:] -= 0.85 * x_ref[:-1]
        x_deg[1:] -= 0.85 * x_deg[:-1]

        device = next(iter(self.parameters())).device

        x = torch.from_numpy(x_ref).to(device)
        y = torch.from_numpy(x_deg).to(device)

        with torch.no_grad():
            dist = 10 * self.forward(x, y)

        return dist.cpu().numpy().item()


lace_loss = LaceLoss()
device = 'cuda' if torch.cuda.is_available() else 'cpu'
lace_loss.to(device)

def compare(x, y):

    return lace_loss.compare(x, y)