Module audiocraft.losses.stftloss

Classes

class LogSTFTMagnitudeLoss (epsilon: float = 1.1920928955078125e-07)
Expand source code
class LogSTFTMagnitudeLoss(nn.Module):
    """Log STFT magnitude loss.

    Args:
        epsilon (float): Epsilon value for numerical stability.
    """
    def __init__(self, epsilon: float = torch.finfo(torch.float32).eps):
        super().__init__()
        self.epsilon = epsilon

    def forward(self, x_mag: torch.Tensor, y_mag: torch.Tensor):
        """Calculate forward propagation.

        Args:
            x_mag (torch.Tensor): Magnitude spectrogram of predicted signal (B, #frames, #freq_bins).
            y_mag (torch.Tensor): Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins).
        Returns:
            torch.Tensor: Log STFT magnitude loss value.
        """
        return F.l1_loss(torch.log(self.epsilon + y_mag), torch.log(self.epsilon + x_mag))

Log STFT magnitude loss.

Args

epsilon : float
Epsilon value for numerical stability.

Initializes internal Module state, shared by both nn.Module and ScriptModule.

Ancestors

  • torch.nn.modules.module.Module

Class variables

var call_super_init : bool
var dump_patches : bool
var training : bool

Methods

def forward(self, x_mag: torch.Tensor, y_mag: torch.Tensor) ‑> Callable[..., Any]
Expand source code
def forward(self, x_mag: torch.Tensor, y_mag: torch.Tensor):
    """Calculate forward propagation.

    Args:
        x_mag (torch.Tensor): Magnitude spectrogram of predicted signal (B, #frames, #freq_bins).
        y_mag (torch.Tensor): Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins).
    Returns:
        torch.Tensor: Log STFT magnitude loss value.
    """
    return F.l1_loss(torch.log(self.epsilon + y_mag), torch.log(self.epsilon + x_mag))

Calculate forward propagation.

Args

x_mag : torch.Tensor
Magnitude spectrogram of predicted signal (B, #frames, #freq_bins).
y_mag : torch.Tensor
Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins).

Returns

torch.Tensor
Log STFT magnitude loss value.
class MRSTFTLoss (n_ffts: Sequence[int] = [1024, 2048, 512],
hop_lengths: Sequence[int] = [120, 240, 50],
win_lengths: Sequence[int] = [600, 1200, 240],
window: str = 'hann_window',
factor_sc: float = 0.1,
factor_mag: float = 0.1,
normalized: bool = False,
epsilon: float = 1.1920928955078125e-07)
Expand source code
class MRSTFTLoss(nn.Module):
    """Multi resolution STFT loss.

    Args:
        n_ffts (Sequence[int]): Sequence of FFT sizes.
        hop_lengths (Sequence[int]): Sequence of hop sizes.
        win_lengths (Sequence[int]): Sequence of window lengths.
        window (str): Window function type.
        factor_sc (float): Coefficient for the spectral loss.
        factor_mag (float): Coefficient for the magnitude loss.
        normalized (bool): Whether to use normalized STFT or not.
        epsilon (float): Epsilon for numerical stability.
    """
    def __init__(self, n_ffts: tp.Sequence[int] = [1024, 2048, 512], hop_lengths: tp.Sequence[int] = [120, 240, 50],
                 win_lengths: tp.Sequence[int] = [600, 1200, 240], window: str = "hann_window",
                 factor_sc: float = 0.1, factor_mag: float = 0.1,
                 normalized: bool = False, epsilon: float = torch.finfo(torch.float32).eps):
        super().__init__()
        assert len(n_ffts) == len(hop_lengths) == len(win_lengths)
        self.stft_losses = torch.nn.ModuleList()
        for fs, ss, wl in zip(n_ffts, hop_lengths, win_lengths):
            self.stft_losses += [STFTLosses(fs, ss, wl, window, normalized, epsilon)]
        self.factor_sc = factor_sc
        self.factor_mag = factor_mag

    def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
        """Calculate forward propagation.

        Args:
            x (torch.Tensor): Predicted signal (B, T).
            y (torch.Tensor): Groundtruth signal (B, T).
        Returns:
            torch.Tensor: Multi resolution STFT loss.
        """
        sc_loss = torch.Tensor([0.0])
        mag_loss = torch.Tensor([0.0])
        for f in self.stft_losses:
            sc_l, mag_l = f(x, y)
            sc_loss += sc_l
            mag_loss += mag_l
        sc_loss /= len(self.stft_losses)
        mag_loss /= len(self.stft_losses)

        return self.factor_sc * sc_loss + self.factor_mag * mag_loss

Multi resolution STFT loss.

Args

n_ffts : Sequence[int]
Sequence of FFT sizes.
hop_lengths : Sequence[int]
Sequence of hop sizes.
win_lengths : Sequence[int]
Sequence of window lengths.
window : str
Window function type.
factor_sc : float
Coefficient for the spectral loss.
factor_mag : float
Coefficient for the magnitude loss.
normalized : bool
Whether to use normalized STFT or not.
epsilon : float
Epsilon for numerical stability.

Initializes internal Module state, shared by both nn.Module and ScriptModule.

Ancestors

  • torch.nn.modules.module.Module

Class variables

var call_super_init : bool
var dump_patches : bool
var training : bool

Methods

def forward(self, x: torch.Tensor, y: torch.Tensor) ‑> torch.Tensor
Expand source code
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    """Calculate forward propagation.

    Args:
        x (torch.Tensor): Predicted signal (B, T).
        y (torch.Tensor): Groundtruth signal (B, T).
    Returns:
        torch.Tensor: Multi resolution STFT loss.
    """
    sc_loss = torch.Tensor([0.0])
    mag_loss = torch.Tensor([0.0])
    for f in self.stft_losses:
        sc_l, mag_l = f(x, y)
        sc_loss += sc_l
        mag_loss += mag_l
    sc_loss /= len(self.stft_losses)
    mag_loss /= len(self.stft_losses)

    return self.factor_sc * sc_loss + self.factor_mag * mag_loss

Calculate forward propagation.

Args

x : torch.Tensor
Predicted signal (B, T).
y : torch.Tensor
Groundtruth signal (B, T).

Returns

torch.Tensor
Multi resolution STFT loss.
class STFTLoss (n_fft: int = 1024,
hop_length: int = 120,
win_length: int = 600,
window: str = 'hann_window',
normalized: bool = False,
factor_sc: float = 0.1,
factor_mag: float = 0.1,
epsilon: float = 1.1920928955078125e-07)
Expand source code
class STFTLoss(nn.Module):
    """Single Resolution STFT loss.

    Args:
        n_fft (int): Nb of FFT.
        hop_length (int): Hop length.
        win_length (int): Window length.
        window (str): Window function type.
        normalized (bool): Whether to use normalized STFT or not.
        epsilon (float): Epsilon for numerical stability.
        factor_sc (float): Coefficient for the spectral loss.
        factor_mag (float): Coefficient for the magnitude loss.
    """
    def __init__(self, n_fft: int = 1024, hop_length: int = 120, win_length: int = 600,
                 window: str = "hann_window", normalized: bool = False,
                 factor_sc: float = 0.1, factor_mag: float = 0.1,
                 epsilon: float = torch.finfo(torch.float32).eps):
        super().__init__()
        self.loss = STFTLosses(n_fft, hop_length, win_length, window, normalized, epsilon)
        self.factor_sc = factor_sc
        self.factor_mag = factor_mag

    def forward(self, x: torch.Tensor, y: torch.Tensor) -> tp.Tuple[torch.Tensor, torch.Tensor]:
        """Calculate forward propagation.

        Args:
            x (torch.Tensor): Predicted signal (B, T).
            y (torch.Tensor): Groundtruth signal (B, T).
        Returns:
            torch.Tensor: Single resolution STFT loss.
        """
        sc_loss, mag_loss = self.loss(x, y)
        return self.factor_sc * sc_loss + self.factor_mag * mag_loss

Single Resolution STFT loss.

Args

n_fft : int
Nb of FFT.
hop_length : int
Hop length.
win_length : int
Window length.
window : str
Window function type.
normalized : bool
Whether to use normalized STFT or not.
epsilon : float
Epsilon for numerical stability.
factor_sc : float
Coefficient for the spectral loss.
factor_mag : float
Coefficient for the magnitude loss.

Initializes internal Module state, shared by both nn.Module and ScriptModule.

Ancestors

  • torch.nn.modules.module.Module

Class variables

var call_super_init : bool
var dump_patches : bool
var training : bool

Methods

def forward(self, x: torch.Tensor, y: torch.Tensor) ‑> Tuple[torch.Tensor, torch.Tensor]
Expand source code
def forward(self, x: torch.Tensor, y: torch.Tensor) -> tp.Tuple[torch.Tensor, torch.Tensor]:
    """Calculate forward propagation.

    Args:
        x (torch.Tensor): Predicted signal (B, T).
        y (torch.Tensor): Groundtruth signal (B, T).
    Returns:
        torch.Tensor: Single resolution STFT loss.
    """
    sc_loss, mag_loss = self.loss(x, y)
    return self.factor_sc * sc_loss + self.factor_mag * mag_loss

Calculate forward propagation.

Args

x : torch.Tensor
Predicted signal (B, T).
y : torch.Tensor
Groundtruth signal (B, T).

Returns

torch.Tensor
Single resolution STFT loss.
class STFTLosses (n_fft: int = 1024,
hop_length: int = 120,
win_length: int = 600,
window: str = 'hann_window',
normalized: bool = False,
epsilon: float = 1.1920928955078125e-07)
Expand source code
class STFTLosses(nn.Module):
    """STFT losses.

    Args:
        n_fft (int): Size of FFT.
        hop_length (int): Hop length.
        win_length (int): Window length.
        window (str): Window function type.
        normalized (bool): Whether to use normalized STFT or not.
        epsilon (float): Epsilon for numerical stability.
    """
    def __init__(self, n_fft: int = 1024, hop_length: int = 120, win_length: int = 600,
                 window: str = "hann_window", normalized: bool = False,
                 epsilon: float = torch.finfo(torch.float32).eps):
        super().__init__()
        self.n_fft = n_fft
        self.hop_length = hop_length
        self.win_length = win_length
        self.normalized = normalized
        self.register_buffer("window", getattr(torch, window)(win_length))
        self.spectral_convergenge_loss = SpectralConvergenceLoss(epsilon)
        self.log_stft_magnitude_loss = LogSTFTMagnitudeLoss(epsilon)

    def forward(self, x: torch.Tensor, y: torch.Tensor) -> tp.Tuple[torch.Tensor, torch.Tensor]:
        """Calculate forward propagation.

        Args:
            x (torch.Tensor): Predicted signal (B, T).
            y (torch.Tensor): Groundtruth signal (B, T).
        Returns:
            torch.Tensor: Spectral convergence loss value.
            torch.Tensor: Log STFT magnitude loss value.
        """
        x_mag = _stft(x, self.n_fft, self.hop_length,
                      self.win_length, self.window, self.normalized)  # type: ignore
        y_mag = _stft(y, self.n_fft, self.hop_length,
                      self.win_length, self.window, self.normalized)  # type: ignore
        sc_loss = self.spectral_convergenge_loss(x_mag, y_mag)
        mag_loss = self.log_stft_magnitude_loss(x_mag, y_mag)

        return sc_loss, mag_loss

STFT losses.

Args

n_fft : int
Size of FFT.
hop_length : int
Hop length.
win_length : int
Window length.
window : str
Window function type.
normalized : bool
Whether to use normalized STFT or not.
epsilon : float
Epsilon for numerical stability.

Initializes internal Module state, shared by both nn.Module and ScriptModule.

Ancestors

  • torch.nn.modules.module.Module

Class variables

var call_super_init : bool
var dump_patches : bool
var training : bool

Methods

def forward(self, x: torch.Tensor, y: torch.Tensor) ‑> Tuple[torch.Tensor, torch.Tensor]
Expand source code
def forward(self, x: torch.Tensor, y: torch.Tensor) -> tp.Tuple[torch.Tensor, torch.Tensor]:
    """Calculate forward propagation.

    Args:
        x (torch.Tensor): Predicted signal (B, T).
        y (torch.Tensor): Groundtruth signal (B, T).
    Returns:
        torch.Tensor: Spectral convergence loss value.
        torch.Tensor: Log STFT magnitude loss value.
    """
    x_mag = _stft(x, self.n_fft, self.hop_length,
                  self.win_length, self.window, self.normalized)  # type: ignore
    y_mag = _stft(y, self.n_fft, self.hop_length,
                  self.win_length, self.window, self.normalized)  # type: ignore
    sc_loss = self.spectral_convergenge_loss(x_mag, y_mag)
    mag_loss = self.log_stft_magnitude_loss(x_mag, y_mag)

    return sc_loss, mag_loss

Calculate forward propagation.

Args

x : torch.Tensor
Predicted signal (B, T).
y : torch.Tensor
Groundtruth signal (B, T).

Returns

torch.Tensor
Spectral convergence loss value.
torch.Tensor
Log STFT magnitude loss value.
class SpectralConvergenceLoss (epsilon: float = 1.1920928955078125e-07)
Expand source code
class SpectralConvergenceLoss(nn.Module):
    """Spectral convergence loss.
    """
    def __init__(self, epsilon: float = torch.finfo(torch.float32).eps):
        super().__init__()
        self.epsilon = epsilon

    def forward(self, x_mag: torch.Tensor, y_mag: torch.Tensor):
        """Calculate forward propagation.

        Args:
            x_mag: Magnitude spectrogram of predicted signal (B, #frames, #freq_bins).
            y_mag: Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins).
        Returns:
            torch.Tensor: Spectral convergence loss value.
        """
        return torch.norm(y_mag - x_mag, p="fro") / (torch.norm(y_mag, p="fro") + self.epsilon)

Spectral convergence loss.

Initializes internal Module state, shared by both nn.Module and ScriptModule.

Ancestors

  • torch.nn.modules.module.Module

Class variables

var call_super_init : bool
var dump_patches : bool
var training : bool

Methods

def forward(self, x_mag: torch.Tensor, y_mag: torch.Tensor) ‑> Callable[..., Any]
Expand source code
def forward(self, x_mag: torch.Tensor, y_mag: torch.Tensor):
    """Calculate forward propagation.

    Args:
        x_mag: Magnitude spectrogram of predicted signal (B, #frames, #freq_bins).
        y_mag: Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins).
    Returns:
        torch.Tensor: Spectral convergence loss value.
    """
    return torch.norm(y_mag - x_mag, p="fro") / (torch.norm(y_mag, p="fro") + self.epsilon)

Calculate forward propagation.

Args

x_mag
Magnitude spectrogram of predicted signal (B, #frames, #freq_bins).
y_mag
Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins).

Returns

torch.Tensor
Spectral convergence loss value.