Spaces:
Runtime error
Runtime error
Create stft_loss.py
Browse files- stft_loss.py +174 -0
stft_loss.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapted from https://github.com/kan-bayashi/ParallelWaveGAN
|
2 |
+
|
3 |
+
# Original Copyright 2019 Tomoki Hayashi
|
4 |
+
# MIT License (https://opensource.org/licenses/MIT)
|
5 |
+
|
6 |
+
"""STFT-based Loss modules."""
|
7 |
+
|
8 |
+
import torch
|
9 |
+
import torch.nn.functional as F
|
10 |
+
|
11 |
+
from distutils.version import LooseVersion
|
12 |
+
|
13 |
+
is_pytorch_17plus = LooseVersion(torch.__version__) >= LooseVersion("1.7")
|
14 |
+
|
15 |
+
torch.manual_seed(0)
|
16 |
+
|
17 |
+
|
18 |
+
def stft(x, fft_size, hop_size, win_length, window):
|
19 |
+
"""Perform STFT and convert to magnitude spectrogram.
|
20 |
+
Args:
|
21 |
+
x (Tensor): Input signal tensor (B, T).
|
22 |
+
fft_size (int): FFT size.
|
23 |
+
hop_size (int): Hop size.
|
24 |
+
win_length (int): Window length.
|
25 |
+
window (str): Window function type.
|
26 |
+
Returns:
|
27 |
+
Tensor: Magnitude spectrogram (B, #frames, fft_size // 2 + 1).
|
28 |
+
"""
|
29 |
+
if is_pytorch_17plus:
|
30 |
+
x_stft = torch.stft(
|
31 |
+
x, fft_size, hop_size, win_length, window, return_complex=False
|
32 |
+
)
|
33 |
+
else:
|
34 |
+
x_stft = torch.stft(x, fft_size, hop_size, win_length, window)
|
35 |
+
real = x_stft[..., 0]
|
36 |
+
imag = x_stft[..., 1]
|
37 |
+
|
38 |
+
# NOTE(kan-bayashi): clamp is needed to avoid nan or inf
|
39 |
+
return torch.sqrt(torch.clamp(real**2 + imag**2, min=1e-7)).transpose(2, 1)
|
40 |
+
|
41 |
+
|
42 |
+
class SpectralConvergenceLoss(torch.nn.Module):
|
43 |
+
"""Spectral convergence loss module."""
|
44 |
+
|
45 |
+
def __init__(self):
|
46 |
+
"""Initilize spectral convergence loss module."""
|
47 |
+
super(SpectralConvergenceLoss, self).__init__()
|
48 |
+
|
49 |
+
def forward(self, x_mag, y_mag):
|
50 |
+
"""Calculate forward propagation.
|
51 |
+
Args:
|
52 |
+
x_mag (Tensor): Magnitude spectrogram of predicted signal (B, #frames, #freq_bins).
|
53 |
+
y_mag (Tensor): Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins).
|
54 |
+
|
55 |
+
Returns:
|
56 |
+
Tensor: Spectral convergence loss value.
|
57 |
+
|
58 |
+
"""
|
59 |
+
return torch.norm(y_mag - x_mag, p="fro") / torch.norm(y_mag, p="fro")
|
60 |
+
|
61 |
+
|
62 |
+
class LogSTFTMagnitudeLoss(torch.nn.Module):
|
63 |
+
"""Log STFT magnitude loss module."""
|
64 |
+
|
65 |
+
def __init__(self):
|
66 |
+
"""Initilize los STFT magnitude loss module."""
|
67 |
+
super(LogSTFTMagnitudeLoss, self).__init__()
|
68 |
+
|
69 |
+
def forward(self, x_mag, y_mag):
|
70 |
+
"""Calculate forward propagation.
|
71 |
+
Args:
|
72 |
+
x_mag (Tensor): Magnitude spectrogram of predicted signal (B, #frames, #freq_bins).
|
73 |
+
y_mag (Tensor): Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins).
|
74 |
+
|
75 |
+
Returns:
|
76 |
+
Tensor: Log STFT magnitude loss value.
|
77 |
+
"""
|
78 |
+
return F.l1_loss(torch.log(y_mag), torch.log(x_mag))
|
79 |
+
|
80 |
+
|
81 |
+
class STFTLoss(torch.nn.Module):
|
82 |
+
"""STFT loss module."""
|
83 |
+
|
84 |
+
def __init__(
|
85 |
+
self, fft_size=1024, shift_size=120, win_length=600, window="hann_window",
|
86 |
+
band="full"
|
87 |
+
):
|
88 |
+
"""Initialize STFT loss module."""
|
89 |
+
super(STFTLoss, self).__init__()
|
90 |
+
self.fft_size = fft_size
|
91 |
+
self.shift_size = shift_size
|
92 |
+
self.win_length = win_length
|
93 |
+
self.band = band
|
94 |
+
|
95 |
+
self.spectral_convergence_loss = SpectralConvergenceLoss()
|
96 |
+
self.log_stft_magnitude_loss = LogSTFTMagnitudeLoss()
|
97 |
+
# NOTE(kan-bayashi): Use register_buffer to fix #223
|
98 |
+
self.register_buffer("window", getattr(torch, window)(win_length))
|
99 |
+
|
100 |
+
def forward(self, x, y):
|
101 |
+
"""Calculate forward propagation.
|
102 |
+
Args:
|
103 |
+
x (Tensor): Predicted signal (B, T).
|
104 |
+
y (Tensor): Groundtruth signal (B, T).
|
105 |
+
Returns:
|
106 |
+
Tensor: Spectral convergence loss value.
|
107 |
+
Tensor: Log STFT magnitude loss value.
|
108 |
+
"""
|
109 |
+
x_mag = stft(x, self.fft_size, self.shift_size, self.win_length, self.window)
|
110 |
+
y_mag = stft(y, self.fft_size, self.shift_size, self.win_length, self.window)
|
111 |
+
|
112 |
+
if self.band == "high":
|
113 |
+
freq_mask_ind = x_mag.shape[1] // 2 # only select high frequency bands
|
114 |
+
sc_loss = self.spectral_convergence_loss(x_mag[:,freq_mask_ind:,:], y_mag[:,freq_mask_ind:,:])
|
115 |
+
mag_loss = self.log_stft_magnitude_loss(x_mag[:,freq_mask_ind:,:], y_mag[:,freq_mask_ind:,:])
|
116 |
+
elif self.band == "full":
|
117 |
+
sc_loss = self.spectral_convergence_loss(x_mag, y_mag)
|
118 |
+
mag_loss = self.log_stft_magnitude_loss(x_mag, y_mag)
|
119 |
+
else:
|
120 |
+
raise NotImplementedError
|
121 |
+
|
122 |
+
return sc_loss, mag_loss
|
123 |
+
|
124 |
+
|
125 |
+
class MultiResolutionSTFTLoss(torch.nn.Module):
|
126 |
+
"""Multi resolution STFT loss module."""
|
127 |
+
|
128 |
+
def __init__(
|
129 |
+
self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240],
|
130 |
+
window="hann_window", sc_lambda=0.1, mag_lambda=0.1, band="full"
|
131 |
+
):
|
132 |
+
"""Initialize Multi resolution STFT loss module.
|
133 |
+
Args:
|
134 |
+
fft_sizes (list): List of FFT sizes.
|
135 |
+
hop_sizes (list): List of hop sizes.
|
136 |
+
win_lengths (list): List of window lengths.
|
137 |
+
window (str): Window function type.
|
138 |
+
*_lambda (float): a balancing factor across different losses.
|
139 |
+
band (str): high-band or full-band loss
|
140 |
+
"""
|
141 |
+
super(MultiResolutionSTFTLoss, self).__init__()
|
142 |
+
self.sc_lambda = sc_lambda
|
143 |
+
self.mag_lambda = mag_lambda
|
144 |
+
|
145 |
+
assert len(fft_sizes) == len(hop_sizes) == len(win_lengths)
|
146 |
+
self.stft_losses = torch.nn.ModuleList()
|
147 |
+
for fs, ss, wl in zip(fft_sizes, hop_sizes, win_lengths):
|
148 |
+
self.stft_losses += [STFTLoss(fs, ss, wl, window, band)]
|
149 |
+
|
150 |
+
def forward(self, x, y):
|
151 |
+
"""Calculate forward propagation.
|
152 |
+
Args:
|
153 |
+
x (Tensor): Predicted signal (B, T) or (B, #subband, T).
|
154 |
+
y (Tensor): Groundtruth signal (B, T) or (B, #subband, T).
|
155 |
+
Returns:
|
156 |
+
Tensor: Multi resolution spectral convergence loss value.
|
157 |
+
Tensor: Multi resolution log STFT magnitude loss value.
|
158 |
+
"""
|
159 |
+
if len(x.shape) == 3:
|
160 |
+
x = x.view(-1, x.size(2)) # (B, C, T) -> (B x C, T)
|
161 |
+
y = y.view(-1, y.size(2)) # (B, C, T) -> (B x C, T)
|
162 |
+
sc_loss = 0.0
|
163 |
+
mag_loss = 0.0
|
164 |
+
for f in self.stft_losses:
|
165 |
+
sc_l, mag_l = f(x, y)
|
166 |
+
sc_loss += sc_l
|
167 |
+
mag_loss += mag_l
|
168 |
+
|
169 |
+
sc_loss *= self.sc_lambda
|
170 |
+
sc_loss /= len(self.stft_losses)
|
171 |
+
mag_loss *= self.mag_lambda
|
172 |
+
mag_loss /= len(self.stft_losses)
|
173 |
+
|
174 |
+
return sc_loss, mag_loss
|