From d72b12cf8b5d9b80acdbe8082f0451389afc6407 Mon Sep 17 00:00:00 2001 From: "Kai Li (李凯)" Date: Sat, 7 Sep 2024 01:23:39 +0800 Subject: First Commit --- look2hear/utils/__init__.py | 53 ++ look2hear/utils/complex_utils.py | 191 ++++++++ look2hear/utils/get_layer_from_string.py | 43 ++ look2hear/utils/inversible_interface.py | 13 + look2hear/utils/lightning_utils.py | 110 +++++ look2hear/utils/nets_utils.py | 503 +++++++++++++++++++ look2hear/utils/parser_utils.py | 178 +++++++ look2hear/utils/pylogger.py | 54 +++ look2hear/utils/separator.py | 138 ++++++ look2hear/utils/stft.py | 797 +++++++++++++++++++++++++++++++ look2hear/utils/torch_utils.py | 49 ++ 11 files changed, 2129 insertions(+) create mode 100644 look2hear/utils/__init__.py create mode 100644 look2hear/utils/complex_utils.py create mode 100644 look2hear/utils/get_layer_from_string.py create mode 100644 look2hear/utils/inversible_interface.py create mode 100644 look2hear/utils/lightning_utils.py create mode 100644 look2hear/utils/nets_utils.py create mode 100644 look2hear/utils/parser_utils.py create mode 100644 look2hear/utils/pylogger.py create mode 100644 look2hear/utils/separator.py create mode 100644 look2hear/utils/stft.py create mode 100644 look2hear/utils/torch_utils.py (limited to 'look2hear/utils') diff --git a/look2hear/utils/__init__.py b/look2hear/utils/__init__.py new file mode 100644 index 0000000..7ae4bca --- /dev/null +++ b/look2hear/utils/__init__.py @@ -0,0 +1,53 @@ +### +# Author: Kai Li +# Date: 2021-06-18 16:53:49 +# LastEditors: Please set LastEditors +# LastEditTime: 2024-01-22 01:01:02 +### +from .stft import STFT +from .torch_utils import pad_x_to_y, shape_reconstructed, tensors_to_device +from .parser_utils import ( + prepare_parser_from_dict, + parse_args_as_dict, + str_int_float, + str2bool, + str2bool_arg, + isfloat, + isint, + instantiate +) +from .lightning_utils import print_only, RichProgressBarTheme, MyRichProgressBar, BatchesProcessedColumn, MyMetricsTextColumn +from .complex_utils import is_complex, is_torch_complex_tensor, new_complex_like +from .get_layer_from_string import get_layer +from .inversible_interface import InversibleInterface +from .nets_utils import make_pad_mask +from .pylogger import RankedLogger +from .separator import wav_chunk_inference + +__all__ = [ + "wav_chunk_inference", + "RankedLogger", + "instantiate", + "STFT", + "pad_x_to_y", + "shape_reconstructed", + "tensors_to_device", + "prepare_parser_from_dict", + "parse_args_as_dict", + "str_int_float", + "str2bool", + "str2bool_arg", + "isfloat", + "isint", + "print_only", + "RichProgressBarTheme", + "MyRichProgressBar", + "BatchesProcessedColumn", + "MyMetricsTextColumn", + "is_complex", + "is_torch_complex_tensor", + "new_complex_like", + "get_layer", + "InversibleInterface", + "make_pad_mask", +] diff --git a/look2hear/utils/complex_utils.py b/look2hear/utils/complex_utils.py new file mode 100644 index 0000000..2e35319 --- /dev/null +++ b/look2hear/utils/complex_utils.py @@ -0,0 +1,191 @@ +"""Beamformer module.""" +from typing import Sequence, Tuple, Union + +import torch +from packaging.version import parse as V +from torch_complex import functional as FC +from torch_complex.tensor import ComplexTensor + +EPS = torch.finfo(torch.double).eps +is_torch_1_8_plus = V(torch.__version__) >= V("1.8.0") +is_torch_1_9_plus = V(torch.__version__) >= V("1.9.0") + + +def new_complex_like( + ref: Union[torch.Tensor, ComplexTensor], + real_imag: Tuple[torch.Tensor, torch.Tensor], +): + if isinstance(ref, ComplexTensor): + return ComplexTensor(*real_imag) + elif is_torch_complex_tensor(ref): + return torch.complex(*real_imag) + else: + raise ValueError( + "Please update your PyTorch version to 1.9+ for complex support." + ) + + +def is_torch_complex_tensor(c): + return ( + not isinstance(c, ComplexTensor) and is_torch_1_9_plus and torch.is_complex(c) + ) + + +def is_complex(c): + return isinstance(c, ComplexTensor) or is_torch_complex_tensor(c) + + +def to_double(c): + if not isinstance(c, ComplexTensor) and is_torch_1_9_plus and torch.is_complex(c): + return c.to(dtype=torch.complex128) + else: + return c.double() + + +def to_float(c): + if not isinstance(c, ComplexTensor) and is_torch_1_9_plus and torch.is_complex(c): + return c.to(dtype=torch.complex64) + else: + return c.float() + + +def cat(seq: Sequence[Union[ComplexTensor, torch.Tensor]], *args, **kwargs): + if not isinstance(seq, (list, tuple)): + raise TypeError( + "cat(): argument 'tensors' (position 1) must be tuple of Tensors, " + "not Tensor" + ) + if isinstance(seq[0], ComplexTensor): + return FC.cat(seq, *args, **kwargs) + else: + return torch.cat(seq, *args, **kwargs) + + +def complex_norm( + c: Union[torch.Tensor, ComplexTensor], dim=-1, keepdim=False +) -> torch.Tensor: + if not is_complex(c): + raise TypeError("Input is not a complex tensor.") + if is_torch_complex_tensor(c): + return torch.norm(c, dim=dim, keepdim=keepdim) + else: + if dim is None: + return torch.sqrt((c.real**2 + c.imag**2).sum() + EPS) + else: + return torch.sqrt( + (c.real**2 + c.imag**2).sum(dim=dim, keepdim=keepdim) + EPS + ) + + +def einsum(equation, *operands): + # NOTE: Do not mix ComplexTensor and torch.complex in the input! + # NOTE (wangyou): Until PyTorch 1.9.0, torch.einsum does not support + # mixed input with complex and real tensors. + if len(operands) == 1: + if isinstance(operands[0], (tuple, list)): + operands = operands[0] + complex_module = FC if isinstance(operands[0], ComplexTensor) else torch + return complex_module.einsum(equation, *operands) + elif len(operands) != 2: + op0 = operands[0] + same_type = all(op.dtype == op0.dtype for op in operands[1:]) + if same_type: + _einsum = FC.einsum if isinstance(op0, ComplexTensor) else torch.einsum + return _einsum(equation, *operands) + else: + raise ValueError("0 or More than 2 operands are not supported.") + a, b = operands + if isinstance(a, ComplexTensor) or isinstance(b, ComplexTensor): + return FC.einsum(equation, a, b) + elif is_torch_1_9_plus and (torch.is_complex(a) or torch.is_complex(b)): + if not torch.is_complex(a): + o_real = torch.einsum(equation, a, b.real) + o_imag = torch.einsum(equation, a, b.imag) + return torch.complex(o_real, o_imag) + elif not torch.is_complex(b): + o_real = torch.einsum(equation, a.real, b) + o_imag = torch.einsum(equation, a.imag, b) + return torch.complex(o_real, o_imag) + else: + return torch.einsum(equation, a, b) + else: + return torch.einsum(equation, a, b) + + +def inverse( + c: Union[torch.Tensor, ComplexTensor] +) -> Union[torch.Tensor, ComplexTensor]: + if isinstance(c, ComplexTensor): + return c.inverse2() + else: + return c.inverse() + + +def matmul( + a: Union[torch.Tensor, ComplexTensor], b: Union[torch.Tensor, ComplexTensor] +) -> Union[torch.Tensor, ComplexTensor]: + # NOTE: Do not mix ComplexTensor and torch.complex in the input! + # NOTE (wangyou): Until PyTorch 1.9.0, torch.matmul does not support + # multiplication between complex and real tensors. + if isinstance(a, ComplexTensor) or isinstance(b, ComplexTensor): + return FC.matmul(a, b) + elif is_torch_1_9_plus and (torch.is_complex(a) or torch.is_complex(b)): + if not torch.is_complex(a): + o_real = torch.matmul(a, b.real) + o_imag = torch.matmul(a, b.imag) + return torch.complex(o_real, o_imag) + elif not torch.is_complex(b): + o_real = torch.matmul(a.real, b) + o_imag = torch.matmul(a.imag, b) + return torch.complex(o_real, o_imag) + else: + return torch.matmul(a, b) + else: + return torch.matmul(a, b) + + +def trace(a: Union[torch.Tensor, ComplexTensor]): + # NOTE (wangyou): until PyTorch 1.9.0, torch.trace does not + # support bacth processing. Use FC.trace() as fallback. + return FC.trace(a) + + +def reverse(a: Union[torch.Tensor, ComplexTensor], dim=0): + if isinstance(a, ComplexTensor): + return FC.reverse(a, dim=dim) + else: + return torch.flip(a, dims=(dim,)) + + +def solve(b: Union[torch.Tensor, ComplexTensor], a: Union[torch.Tensor, ComplexTensor]): + """Solve the linear equation ax = b.""" + # NOTE: Do not mix ComplexTensor and torch.complex in the input! + # NOTE (wangyou): Until PyTorch 1.9.0, torch.solve does not support + # mixed input with complex and real tensors. + if isinstance(a, ComplexTensor) or isinstance(b, ComplexTensor): + if isinstance(a, ComplexTensor) and isinstance(b, ComplexTensor): + return FC.solve(b, a, return_LU=False) + else: + return matmul(inverse(a), b) + elif is_torch_1_9_plus and (torch.is_complex(a) or torch.is_complex(b)): + if torch.is_complex(a) and torch.is_complex(b): + return torch.linalg.solve(a, b) + else: + return matmul(inverse(a), b) + else: + if is_torch_1_8_plus: + return torch.linalg.solve(a, b) + else: + return torch.solve(b, a)[0] + + +def stack(seq: Sequence[Union[ComplexTensor, torch.Tensor]], *args, **kwargs): + if not isinstance(seq, (list, tuple)): + raise TypeError( + "stack(): argument 'tensors' (position 1) must be tuple of Tensors, " + "not Tensor" + ) + if isinstance(seq[0], ComplexTensor): + return FC.stack(seq, *args, **kwargs) + else: + return torch.stack(seq, *args, **kwargs) \ No newline at end of file diff --git a/look2hear/utils/get_layer_from_string.py b/look2hear/utils/get_layer_from_string.py new file mode 100644 index 0000000..3987a8d --- /dev/null +++ b/look2hear/utils/get_layer_from_string.py @@ -0,0 +1,43 @@ +import difflib + +import torch + + +def get_layer(l_name, library=torch.nn): + """Return layer object handler from library e.g. from torch.nn + + E.g. if l_name=="elu", returns torch.nn.ELU. + + Args: + l_name (string): Case insensitive name for layer in library (e.g. .'elu'). + library (module): Name of library/module where to search for object handler + with l_name e.g. "torch.nn". + + Returns: + layer_handler (object): handler for the requested layer e.g. (torch.nn.ELU) + + """ + + all_torch_layers = [x for x in dir(torch.nn)] + match = [x for x in all_torch_layers if l_name.lower() == x.lower()] + if len(match) == 0: + close_matches = difflib.get_close_matches( + l_name, [x.lower() for x in all_torch_layers] + ) + raise NotImplementedError( + "Layer with name {} not found in {}.\n Closest matches: {}".format( + l_name, str(library), close_matches + ) + ) + elif len(match) > 1: + close_matches = difflib.get_close_matches( + l_name, [x.lower() for x in all_torch_layers] + ) + raise NotImplementedError( + "Multiple matchs for layer with name {} not found in {}.\n " + "All matches: {}".format(l_name, str(library), close_matches) + ) + else: + # valid + layer_handler = getattr(library, match[0]) + return layer_handler \ No newline at end of file diff --git a/look2hear/utils/inversible_interface.py b/look2hear/utils/inversible_interface.py new file mode 100644 index 0000000..919107e --- /dev/null +++ b/look2hear/utils/inversible_interface.py @@ -0,0 +1,13 @@ +from abc import ABC, abstractmethod +from typing import Tuple + +import torch + + +class InversibleInterface(ABC): + @abstractmethod + def inverse( + self, input: torch.Tensor, input_lengths: torch.Tensor = None + ) -> Tuple[torch.Tensor, torch.Tensor]: + # return output, output_lengths + raise NotImplementedError \ No newline at end of file diff --git a/look2hear/utils/lightning_utils.py b/look2hear/utils/lightning_utils.py new file mode 100644 index 0000000..aae49c6 --- /dev/null +++ b/look2hear/utils/lightning_utils.py @@ -0,0 +1,110 @@ +### +# Author: Kai Li +# Date: 2022-05-27 10:27:56 +# Email: lk21@mails.tsinghua.edu.cn +# LastEditTime: 2022-06-13 12:11:15 +### +from rich import print +from dataclasses import dataclass +from pytorch_lightning.utilities import rank_zero_only +from typing import Union +from pytorch_lightning.callbacks.progress.rich_progress import * +from rich.console import Console, RenderableType +from rich.progress_bar import ProgressBar +from rich.style import Style +from rich.text import Text +from rich.progress import ( + BarColumn, + DownloadColumn, + Progress, + TaskID, + TextColumn, + TimeRemainingColumn, + TransferSpeedColumn, + ProgressColumn +) +from rich import print, reconfigure + +@rank_zero_only +def print_only(message: str): + print(message) + +@dataclass +class RichProgressBarTheme: + """Styles to associate to different base components. + + Args: + description: Style for the progress bar description. For eg., Epoch x, Testing, etc. + progress_bar: Style for the bar in progress. + progress_bar_finished: Style for the finished progress bar. + progress_bar_pulse: Style for the progress bar when `IterableDataset` is being processed. + batch_progress: Style for the progress tracker (i.e 10/50 batches completed). + time: Style for the processed time and estimate time remaining. + processing_speed: Style for the speed of the batches being processed. + metrics: Style for the metrics + + https://rich.readthedocs.io/en/stable/style.html + """ + + description: Union[str, Style] = "#FF4500" + progress_bar: Union[str, Style] = "#f92672" + progress_bar_finished: Union[str, Style] = "#b7cc8a" + progress_bar_pulse: Union[str, Style] = "#f92672" + batch_progress: Union[str, Style] = "#fc608a" + time: Union[str, Style] = "#45ada2" + processing_speed: Union[str, Style] = "#DC143C" + metrics: Union[str, Style] = "#228B22" + +class BatchesProcessedColumn(ProgressColumn): + def __init__(self, style: Union[str, Style]): + self.style = style + super().__init__() + + def render(self, task) -> RenderableType: + total = task.total if task.total != float("inf") else "--" + return Text(f"{int(task.completed)}/{int(total)}", style=self.style) + +class MyMetricsTextColumn(ProgressColumn): + """A column containing text.""" + + def __init__(self, style): + self._tasks = {} + self._current_task_id = 0 + self._metrics = {} + self._style = style + super().__init__() + + def update(self, metrics): + # Called when metrics are ready to be rendered. + # This is to prevent render from causing deadlock issues by requesting metrics + # in separate threads. + self._metrics = metrics + + def render(self, task) -> Text: + text = "" + for k, v in self._metrics.items(): + text += f"{k}: {round(v, 3) if isinstance(v, float) else v} " + return Text(text, justify="left", style=self._style) + +class MyRichProgressBar(RichProgressBar): + """A progress bar prints metrics at the end of each epoch + """ + + def _init_progress(self, trainer): + if self.is_enabled and (self.progress is None or self._progress_stopped): + self._reset_progress_bar_ids() + reconfigure(**self._console_kwargs) + # file = open("/home/likai/data/Look2Hear/Experiments/run_logs/EdgeFRCNN-Noncausal.log", 'w') + self._console: Console = Console(force_terminal=True) + self._console.clear_live() + self._metric_component = MetricsTextColumn(trainer, self.theme.metrics) + self.progress = CustomProgress( + *self.configure_columns(trainer), + self._metric_component, + auto_refresh=False, + disable=self.is_disabled, + console=self._console, + ) + self.progress.start() + # progress has started + self._progress_stopped = False \ No newline at end of file diff --git a/look2hear/utils/nets_utils.py b/look2hear/utils/nets_utils.py new file mode 100644 index 0000000..e7a6770 --- /dev/null +++ b/look2hear/utils/nets_utils.py @@ -0,0 +1,503 @@ +# -*- coding: utf-8 -*- + +"""Network related utility tools.""" + +import logging +from typing import Dict + +import numpy as np +import torch + + +def to_device(m, x): + """Send tensor into the device of the module. + + Args: + m (torch.nn.Module): Torch module. + x (Tensor): Torch tensor. + + Returns: + Tensor: Torch tensor located in the same place as torch module. + + """ + if isinstance(m, torch.nn.Module): + device = next(m.parameters()).device + elif isinstance(m, torch.Tensor): + device = m.device + else: + raise TypeError( + "Expected torch.nn.Module or torch.tensor, " f"bot got: {type(m)}" + ) + return x.to(device) + + +def pad_list(xs, pad_value): + """Perform padding for the list of tensors. + + Args: + xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)]. + pad_value (float): Value for padding. + + Returns: + Tensor: Padded tensor (B, Tmax, `*`). + + Examples: + >>> x = [torch.ones(4), torch.ones(2), torch.ones(1)] + >>> x + [tensor([1., 1., 1., 1.]), tensor([1., 1.]), tensor([1.])] + >>> pad_list(x, 0) + tensor([[1., 1., 1., 1.], + [1., 1., 0., 0.], + [1., 0., 0., 0.]]) + + """ + n_batch = len(xs) + max_len = max(x.size(0) for x in xs) + pad = xs[0].new(n_batch, max_len, *xs[0].size()[1:]).fill_(pad_value) + + for i in range(n_batch): + pad[i, : xs[i].size(0)] = xs[i] + + return pad + + +def make_pad_mask(lengths, xs=None, length_dim=-1, maxlen=None): + """Make mask tensor containing indices of padded part. + + Args: + lengths (LongTensor or List): Batch of lengths (B,). + xs (Tensor, optional): The reference tensor. + If set, masks will be the same shape as this tensor. + length_dim (int, optional): Dimension indicator of the above tensor. + See the example. + + Returns: + Tensor: Mask tensor containing indices of padded part. + dtype=torch.uint8 in PyTorch 1.2- + dtype=torch.bool in PyTorch 1.2+ (including 1.2) + + Examples: + With only lengths. + + >>> lengths = [5, 3, 2] + >>> make_pad_mask(lengths) + masks = [[0, 0, 0, 0 ,0], + [0, 0, 0, 1, 1], + [0, 0, 1, 1, 1]] + + With the reference tensor. + + >>> xs = torch.zeros((3, 2, 4)) + >>> make_pad_mask(lengths, xs) + tensor([[[0, 0, 0, 0], + [0, 0, 0, 0]], + [[0, 0, 0, 1], + [0, 0, 0, 1]], + [[0, 0, 1, 1], + [0, 0, 1, 1]]], dtype=torch.uint8) + >>> xs = torch.zeros((3, 2, 6)) + >>> make_pad_mask(lengths, xs) + tensor([[[0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1]], + [[0, 0, 0, 1, 1, 1], + [0, 0, 0, 1, 1, 1]], + [[0, 0, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1]]], dtype=torch.uint8) + + With the reference tensor and dimension indicator. + + >>> xs = torch.zeros((3, 6, 6)) + >>> make_pad_mask(lengths, xs, 1) + tensor([[[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1]], + [[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1]], + [[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1]]], dtype=torch.uint8) + >>> make_pad_mask(lengths, xs, 2) + tensor([[[0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1]], + [[0, 0, 0, 1, 1, 1], + [0, 0, 0, 1, 1, 1], + [0, 0, 0, 1, 1, 1], + [0, 0, 0, 1, 1, 1], + [0, 0, 0, 1, 1, 1], + [0, 0, 0, 1, 1, 1]], + [[0, 0, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1]]], dtype=torch.uint8) + + """ + if length_dim == 0: + raise ValueError("length_dim cannot be 0: {}".format(length_dim)) + + if not isinstance(lengths, list): + lengths = lengths.long().tolist() + + bs = int(len(lengths)) + if maxlen is None: + if xs is None: + maxlen = int(max(lengths)) + else: + maxlen = xs.size(length_dim) + else: + assert xs is None + assert maxlen >= int(max(lengths)) + + seq_range = torch.arange(0, maxlen, dtype=torch.int64) + seq_range_expand = seq_range.unsqueeze(0).expand(bs, maxlen) + seq_length_expand = seq_range_expand.new(lengths).unsqueeze(-1) + mask = seq_range_expand >= seq_length_expand + + if xs is not None: + assert xs.size(0) == bs, (xs.size(0), bs) + + if length_dim < 0: + length_dim = xs.dim() + length_dim + # ind = (:, None, ..., None, :, , None, ..., None) + ind = tuple( + slice(None) if i in (0, length_dim) else None for i in range(xs.dim()) + ) + mask = mask[ind].expand_as(xs).to(xs.device) + return mask + + +def make_non_pad_mask(lengths, xs=None, length_dim=-1): + """Make mask tensor containing indices of non-padded part. + + Args: + lengths (LongTensor or List): Batch of lengths (B,). + xs (Tensor, optional): The reference tensor. + If set, masks will be the same shape as this tensor. + length_dim (int, optional): Dimension indicator of the above tensor. + See the example. + + Returns: + ByteTensor: mask tensor containing indices of padded part. + dtype=torch.uint8 in PyTorch 1.2- + dtype=torch.bool in PyTorch 1.2+ (including 1.2) + + Examples: + With only lengths. + + >>> lengths = [5, 3, 2] + >>> make_non_pad_mask(lengths) + masks = [[1, 1, 1, 1 ,1], + [1, 1, 1, 0, 0], + [1, 1, 0, 0, 0]] + + With the reference tensor. + + >>> xs = torch.zeros((3, 2, 4)) + >>> make_non_pad_mask(lengths, xs) + tensor([[[1, 1, 1, 1], + [1, 1, 1, 1]], + [[1, 1, 1, 0], + [1, 1, 1, 0]], + [[1, 1, 0, 0], + [1, 1, 0, 0]]], dtype=torch.uint8) + >>> xs = torch.zeros((3, 2, 6)) + >>> make_non_pad_mask(lengths, xs) + tensor([[[1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 0]], + [[1, 1, 1, 0, 0, 0], + [1, 1, 1, 0, 0, 0]], + [[1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0]]], dtype=torch.uint8) + + With the reference tensor and dimension indicator. + + >>> xs = torch.zeros((3, 6, 6)) + >>> make_non_pad_mask(lengths, xs, 1) + tensor([[[1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0]], + [[1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]], + [[1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]]], dtype=torch.uint8) + >>> make_non_pad_mask(lengths, xs, 2) + tensor([[[1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 0]], + [[1, 1, 1, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [1, 1, 1, 0, 0, 0]], + [[1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0]]], dtype=torch.uint8) + + """ + return ~make_pad_mask(lengths, xs, length_dim) + + +def mask_by_length(xs, lengths, fill=0): + """Mask tensor according to length. + + Args: + xs (Tensor): Batch of input tensor (B, `*`). + lengths (LongTensor or List): Batch of lengths (B,). + fill (int or float): Value to fill masked part. + + Returns: + Tensor: Batch of masked input tensor (B, `*`). + + Examples: + >>> x = torch.arange(5).repeat(3, 1) + 1 + >>> x + tensor([[1, 2, 3, 4, 5], + [1, 2, 3, 4, 5], + [1, 2, 3, 4, 5]]) + >>> lengths = [5, 3, 2] + >>> mask_by_length(x, lengths) + tensor([[1, 2, 3, 4, 5], + [1, 2, 3, 0, 0], + [1, 2, 0, 0, 0]]) + + """ + assert xs.size(0) == len(lengths) + ret = xs.data.new(*xs.size()).fill_(fill) + for i, l in enumerate(lengths): + ret[i, :l] = xs[i, :l] + return ret + + +def th_accuracy(pad_outputs, pad_targets, ignore_label): + """Calculate accuracy. + + Args: + pad_outputs (Tensor): Prediction tensors (B * Lmax, D). + pad_targets (LongTensor): Target label tensors (B, Lmax, D). + ignore_label (int): Ignore label id. + + Returns: + float: Accuracy value (0.0 - 1.0). + + """ + pad_pred = pad_outputs.view( + pad_targets.size(0), pad_targets.size(1), pad_outputs.size(1) + ).argmax(2) + mask = pad_targets != ignore_label + numerator = torch.sum( + pad_pred.masked_select(mask) == pad_targets.masked_select(mask) + ) + denominator = torch.sum(mask) + return float(numerator) / float(denominator) + + +def to_torch_tensor(x): + """Change to torch.Tensor or ComplexTensor from numpy.ndarray. + + Args: + x: Inputs. It should be one of numpy.ndarray, Tensor, ComplexTensor, and dict. + + Returns: + Tensor or ComplexTensor: Type converted inputs. + + Examples: + >>> xs = np.ones(3, dtype=np.float32) + >>> xs = to_torch_tensor(xs) + tensor([1., 1., 1.]) + >>> xs = torch.ones(3, 4, 5) + >>> assert to_torch_tensor(xs) is xs + >>> xs = {'real': xs, 'imag': xs} + >>> to_torch_tensor(xs) + ComplexTensor( + Real: + tensor([1., 1., 1.]) + Imag; + tensor([1., 1., 1.]) + ) + + """ + # If numpy, change to torch tensor + if isinstance(x, np.ndarray): + if x.dtype.kind == "c": + # Dynamically importing because torch_complex requires python3 + from torch_complex.tensor import ComplexTensor + + return ComplexTensor(x) + else: + return torch.from_numpy(x) + + # If {'real': ..., 'imag': ...}, convert to ComplexTensor + elif isinstance(x, dict): + # Dynamically importing because torch_complex requires python3 + from torch_complex.tensor import ComplexTensor + + if "real" not in x or "imag" not in x: + raise ValueError("has 'real' and 'imag' keys: {}".format(list(x))) + # Relative importing because of using python3 syntax + return ComplexTensor(x["real"], x["imag"]) + + # If torch.Tensor, as it is + elif isinstance(x, torch.Tensor): + return x + + else: + error = ( + "x must be numpy.ndarray, torch.Tensor or a dict like " + "{{'real': torch.Tensor, 'imag': torch.Tensor}}, " + "but got {}".format(type(x)) + ) + try: + from torch_complex.tensor import ComplexTensor + except Exception: + # If PY2 + raise ValueError(error) + else: + # If PY3 + if isinstance(x, ComplexTensor): + return x + else: + raise ValueError(error) + + +def get_subsample(train_args, mode, arch): + """Parse the subsampling factors from the args for the specified `mode` and `arch`. + + Args: + train_args: argument Namespace containing options. + mode: one of ('asr', 'mt', 'st') + arch: one of ('rnn', 'rnn-t', 'rnn_mix', 'rnn_mulenc', 'transformer') + + Returns: + np.ndarray / List[np.ndarray]: subsampling factors. + """ + if arch == "transformer": + return np.array([1]) + + elif mode == "mt" and arch == "rnn": + # +1 means input (+1) and layers outputs (train_args.elayer) + subsample = np.ones(train_args.elayers + 1, dtype=np.int64) + logging.warning("Subsampling is not performed for machine translation.") + logging.info("subsample: " + " ".join([str(x) for x in subsample])) + return subsample + + elif ( + (mode == "asr" and arch in ("rnn", "rnn-t")) + or (mode == "mt" and arch == "rnn") + or (mode == "st" and arch == "rnn") + ): + subsample = np.ones(train_args.elayers + 1, dtype=np.int64) + if train_args.etype.endswith("p") and not train_args.etype.startswith("vgg"): + ss = train_args.subsample.split("_") + for j in range(min(train_args.elayers + 1, len(ss))): + subsample[j] = int(ss[j]) + else: + logging.warning( + "Subsampling is not performed for vgg*. " + "It is performed in max pooling layers at CNN." + ) + logging.info("subsample: " + " ".join([str(x) for x in subsample])) + return subsample + + elif mode == "asr" and arch == "rnn_mix": + subsample = np.ones( + train_args.elayers_sd + train_args.elayers + 1, dtype=np.int64 + ) + if train_args.etype.endswith("p") and not train_args.etype.startswith("vgg"): + ss = train_args.subsample.split("_") + for j in range( + min(train_args.elayers_sd + train_args.elayers + 1, len(ss)) + ): + subsample[j] = int(ss[j]) + else: + logging.warning( + "Subsampling is not performed for vgg*. " + "It is performed in max pooling layers at CNN." + ) + logging.info("subsample: " + " ".join([str(x) for x in subsample])) + return subsample + + elif mode == "asr" and arch == "rnn_mulenc": + subsample_list = [] + for idx in range(train_args.num_encs): + subsample = np.ones(train_args.elayers[idx] + 1, dtype=np.int64) + if train_args.etype[idx].endswith("p") and not train_args.etype[ + idx + ].startswith("vgg"): + ss = train_args.subsample[idx].split("_") + for j in range(min(train_args.elayers[idx] + 1, len(ss))): + subsample[j] = int(ss[j]) + else: + logging.warning( + "Encoder %d: Subsampling is not performed for vgg*. " + "It is performed in max pooling layers at CNN.", + idx + 1, + ) + logging.info("subsample: " + " ".join([str(x) for x in subsample])) + subsample_list.append(subsample) + return subsample_list + + else: + raise ValueError("Invalid options: mode={}, arch={}".format(mode, arch)) + + +def rename_state_dict( + old_prefix: str, new_prefix: str, state_dict: Dict[str, torch.Tensor] +): + """Replace keys of old prefix with new prefix in state dict.""" + # need this list not to break the dict iterator + old_keys = [k for k in state_dict if k.startswith(old_prefix)] + if len(old_keys) > 0: + logging.warning(f"Rename: {old_prefix} -> {new_prefix}") + for k in old_keys: + v = state_dict.pop(k) + new_k = k.replace(old_prefix, new_prefix) + state_dict[new_k] = v + + +def get_activation(act): + """Return activation function.""" + # Lazy load to avoid unused import + from espnet.nets.pytorch_backend.conformer.swish import Swish + + activation_funcs = { + "hardtanh": torch.nn.Hardtanh, + "tanh": torch.nn.Tanh, + "relu": torch.nn.ReLU, + "selu": torch.nn.SELU, + "swish": Swish, + } + + return activation_funcs[act]() \ No newline at end of file diff --git a/look2hear/utils/parser_utils.py b/look2hear/utils/parser_utils.py new file mode 100644 index 0000000..aa99670 --- /dev/null +++ b/look2hear/utils/parser_utils.py @@ -0,0 +1,178 @@ +### +# Author: Kai Li +# Date: 2021-06-20 00:36:46 +# LastEditors: Please set LastEditors +# LastEditTime: 2024-01-22 03:02:57 +### +import sys +import argparse +import importlib +from omegaconf import DictConfig + +def prepare_parser_from_dict(dic, parser=None): + """Prepare an argparser from a dictionary. + + Args: + dic (dict): Two-level config dictionary with unique bottom-level keys. + parser (argparse.ArgumentParser, optional): If a parser already + exists, add the keys from the dictionary on the top of it. + + Returns: + argparse.ArgumentParser: + Parser instance with groups corresponding to the first level keys + and arguments corresponding to the second level keys with default + values given by the values. + """ + + def standardized_entry_type(value): + """If the default value is None, replace NoneType by str_int_float. + If the default value is boolean, look for boolean strings.""" + if value is None: + return str_int_float + if isinstance(str2bool(value), bool): + return str2bool_arg + return type(value) + + if parser is None: + parser = argparse.ArgumentParser() + for k in dic.keys(): + group = parser.add_argument_group(k) + if isinstance(dic[k], list): + entry_type = standardized_entry_type(dic[k]) + group.add_argument("--" + k, default=dic[k], type=entry_type) + elif isinstance(dic[k], dict): + for kk in dic[k].keys(): + entry_type = standardized_entry_type(dic[k][kk]) + group.add_argument("--" + kk, default=dic[k][kk], type=entry_type) + elif isinstance(dic[k], str): + entry_type = standardized_entry_type(dic[k]) + group.add_argument("--" + k, default=dic[k], type=entry_type) + return parser + + +def str_int_float(value): + """Type to convert strings to int, float (in this order) if possible. + + Args: + value (str): Value to convert. + + Returns: + int, float, str: Converted value. + """ + if isint(value): + return int(value) + if isfloat(value): + return float(value) + elif isinstance(value, str): + return value + + +def str2bool(value): + """Type to convert strings to Boolean (returns input if not boolean)""" + if not isinstance(value, str): + return value + if value.lower() in ("yes", "true", "y", "1"): + return True + elif value.lower() in ("no", "false", "n", "0"): + return False + else: + return value + + +def str2bool_arg(value): + """Argparse type to convert strings to Boolean""" + value = str2bool(value) + if isinstance(value, bool): + return value + raise argparse.ArgumentTypeError("Boolean value expected.") + + +def isfloat(value): + """Computes whether `value` can be cast to a float. + + Args: + value (str): Value to check. + + Returns: + bool: Whether `value` can be cast to a float. + + """ + try: + float(value) + return True + except ValueError: + return False + + +def isint(value): + """Computes whether `value` can be cast to an int + + Args: + value (str): Value to check. + + Returns: + bool: Whether `value` can be cast to an int. + + """ + try: + int(value) + return True + except ValueError: + return False + + +def parse_args_as_dict(parser, return_plain_args=False, args=None): + """Get a dict of dicts out of process `parser.parse_args()` + + Top-level keys corresponding to groups and bottom-level keys corresponding + to arguments. Under `'main_args'`, the arguments which don't belong to a + argparse group (i.e main arguments defined before parsing from a dict) can + be found. + + Args: + parser (argparse.ArgumentParser): ArgumentParser instance containing + groups. Output of `prepare_parser_from_dict`. + return_plain_args (bool): Whether to return the output or + `parser.parse_args()`. + args (list): List of arguments as read from the command line. + Used for unit testing. + + Returns: + dict: + Dictionary of dictionaries containing the arguments. Optionally the + direct output `parser.parse_args()`. + """ + args = parser.parse_args(args=args) + args_dic = {} + for group in parser._action_groups: + group_dict = {a.dest: getattr(args, a.dest, None) for a in group._group_actions} + args_dic[group.title] = group_dict + if sys.version_info.minor == 10: + args_dic["main_args"] = args_dic["positional arguments"] + del args_dic["positional arguments"] + else: + args_dic["main_args"] = args_dic["optional arguments"] + del args_dic["optional arguments"] + if return_plain_args: + return args_dic, args + return args_dic + +def instantiate(config, **kwargs): + if '__target__' in config: + module_path, class_name = config['__target__'].rsplit('.', 1) + module = importlib.import_module(module_path) + cls = getattr(module, class_name) + # 先处理嵌套的配置 + params = {} + for key, value in config.items(): + if key != '__target__': + if isinstance(value, DictConfig) and '__target__' in value: + params[key] = instantiate(value) + else: + params[key] = value + # 添加额外的关键字参数 + params.update(kwargs) + return cls(**params) + else: + # 对于不包含 '__target__' 的字典,递归处理其每个值 + return {k: instantiate(v, **kwargs) if isinstance(v, DictConfig) else v for k, v in config.items()} \ No newline at end of file diff --git a/look2hear/utils/pylogger.py b/look2hear/utils/pylogger.py new file mode 100644 index 0000000..cf83129 --- /dev/null +++ b/look2hear/utils/pylogger.py @@ -0,0 +1,54 @@ +import logging +from typing import Mapping, Optional + +from lightning_utilities.core.rank_zero import rank_prefixed_message, rank_zero_only + + +class RankedLogger(logging.LoggerAdapter): + """A multi-GPU-friendly python command line logger.""" + + def __init__( + self, + name: str = __name__, + rank_zero_only: bool = False, + extra: Optional[Mapping[str, object]] = None, + log_file: str = "log.txt", # 添加日志文件名参数 + ) -> None: + logger = logging.getLogger(name) + + # 设置日志格式 + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + + # 添加文件处理器 + file_handler = logging.FileHandler(log_file) + file_handler.setFormatter(formatter) + logger.addHandler(file_handler) + + super().__init__(logger=logger, extra=extra) + self.rank_zero_only = rank_zero_only + + def log(self, level: int, msg: str, rank: Optional[int] = None, *args, **kwargs) -> None: + """Delegate a log call to the underlying logger, after prefixing its message with the rank + of the process it's being logged from. If `'rank'` is provided, then the log will only + occur on that rank/process. + + :param level: The level to log at. Look at `logging.__init__.py` for more information. + :param msg: The message to log. + :param rank: The rank to log at. + :param args: Additional args to pass to the underlying logging function. + :param kwargs: Any additional keyword args to pass to the underlying logging function. + """ + if self.isEnabledFor(level): + msg, kwargs = self.process(msg, kwargs) + current_rank = getattr(rank_zero_only, "rank", None) + if current_rank is None: + raise RuntimeError("The `rank_zero_only.rank` needs to be set before use") + msg = rank_prefixed_message(msg, current_rank) + if self.rank_zero_only: + if current_rank == 0: + self.logger.log(level, msg, *args, **kwargs) + else: + if rank is None: + self.logger.log(level, msg, *args, **kwargs) + elif current_rank == rank: + self.logger.log(level, msg, *args, **kwargs) diff --git a/look2hear/utils/separator.py b/look2hear/utils/separator.py new file mode 100644 index 0000000..0737238 --- /dev/null +++ b/look2hear/utils/separator.py @@ -0,0 +1,138 @@ +### +# Author: Kai Li +# Date: 2021-06-18 16:32:50 +# LastEditors: Kai Li +# LastEditTime: 2021-06-19 01:02:04 +### +import os +import warnings +import torch +import numpy as np +import soundfile as sf + + +def get_device(tensor_or_module, default=None): + if hasattr(tensor_or_module, "device"): + return tensor_or_module.device + elif hasattr(tensor_or_module, "parameters"): + return next(tensor_or_module.parameters()).device + elif default is None: + raise TypeError( + f"Don't know how to get device of {type(tensor_or_module)} object" + ) + else: + return torch.device(default) + + +class Separator: + def forward_wav(self, wav, **kwargs): + raise NotImplementedError + + def sample_rate(self): + raise NotImplementedError + + +def separate(model, wav, **kwargs): + if isinstance(wav, np.ndarray): + return numpy_separate(model, wav, **kwargs) + elif isinstance(wav, torch.Tensor): + return torch_separate(model, wav, **kwargs) + else: + raise ValueError( + f"Only support filenames, numpy arrays and torch tensors, received {type(wav)}" + ) + + +@torch.no_grad() +def torch_separate(model: Separator, wav: torch.Tensor, **kwargs) -> torch.Tensor: + """Core logic of `separate`.""" + if model.in_channels is not None and wav.shape[-2] != model.in_channels: + raise RuntimeError( + f"Model supports {model.in_channels}-channel inputs but found audio with {wav.shape[-2]} channels." + f"Please match the number of channels." + ) + # Handle device placement + input_device = get_device(wav, default="cpu") + model_device = get_device(model, default="cpu") + wav = wav.to(model_device) + # Forward + separate_func = getattr(model, "forward_wav", model) + out_wavs = separate_func(wav, **kwargs) + + # FIXME: for now this is the best we can do. + out_wavs *= wav.abs().sum() / (out_wavs.abs().sum()) + + # Back to input device (and numpy if necessary) + out_wavs = out_wavs.to(input_device) + return out_wavs + + +def numpy_separate(model: Separator, wav: np.ndarray, **kwargs) -> np.ndarray: + """Numpy interface to `separate`.""" + wav = torch.from_numpy(wav) + out_wavs = torch_separate(model, wav, **kwargs) + out_wavs = out_wavs.data.numpy() + return out_wavs + + +def wav_chunk_inference(model, mixture_tensor, sr=16000, target_length=12.0, hop_length=4.0, batch_size=10, n_tracks=3): + """ + Input: + mixture_tensor: Tensor, [nch, input_length] + + Output: + all_target_tensor: Tensor, [nch, n_track, input_length] + """ + batch_mixture = mixture_tensor + + # split data into segments + batch_length = batch_mixture.shape[-1] + + session = int(sr * target_length) + target = int(sr * target_length) + ignore = (session - target) // 2 + hop = int(sr * hop_length) + tr_ratio = target_length / hop_length + if ignore > 0: + zero_pad = torch.zeros(batch_mixture.shape[0], batch_mixture.shape[1], ignore).type(batch_mixture.type()).to(batch_mixture.device) + batch_mixture_pad = torch.cat([zero_pad, batch_mixture, zero_pad], -1) + else: + batch_mixture_pad = batch_mixture + if target - hop > 0: + hop_pad = torch.zeros(batch_mixture.shape[0], batch_mixture.shape[1], target-hop).type(batch_mixture.type()).to(batch_mixture.device) + batch_mixture_pad = torch.cat([hop_pad, batch_mixture_pad, hop_pad], -1) + + skip_idx = ignore + target - hop + zero_pad = torch.zeros(batch_mixture.shape[0], batch_mixture.shape[1], session).type(batch_mixture.type()).to(batch_mixture.device) + num_session = (batch_mixture_pad.shape[-1] - session) // hop + 2 + all_target = torch.zeros(batch_mixture_pad.shape[0], n_tracks, batch_mixture_pad.shape[1], batch_mixture_pad.shape[2]).to(batch_mixture_pad.device) + all_input = [] + all_segment_length = [] + + for i in range(num_session): + this_input = batch_mixture_pad[:,:,i*hop:i*hop+session] + segment_length = this_input.shape[-1] + if segment_length < session: + this_input = torch.cat([this_input, zero_pad[:,:,:session-segment_length]], -1) + all_input.append(this_input) + all_segment_length.append(segment_length) + + all_input = torch.cat(all_input, 0) + num_batch = num_session // batch_size + if num_session % batch_size > 0: + num_batch += 1 + + for i in range(num_batch): + + this_input = all_input[i*batch_size:(i+1)*batch_size] + actual_batch_size = this_input.shape[0] + with torch.no_grad(): + est_target = model(this_input) + # print(est_target.shape) + for j in range(actual_batch_size): + this_est_target = est_target[j,:,:,:all_segment_length[i*batch_size+j]][:,:,ignore:ignore+target].unsqueeze(0) + all_target[:,:,:,ignore+(i*batch_size+j)*hop:ignore+(i*batch_size+j)*hop+target] += this_est_target + + all_target = all_target[:,:,:,skip_idx:skip_idx+batch_length].contiguous() / tr_ratio + + return all_target.squeeze(0) \ No newline at end of file diff --git a/look2hear/utils/stft.py b/look2hear/utils/stft.py new file mode 100644 index 0000000..0bef618 --- /dev/null +++ b/look2hear/utils/stft.py @@ -0,0 +1,797 @@ +# Copyright 2019 Jian Wu +# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) + +import math + +import numpy as np +import torch as th +import torch.nn as nn +import torch.nn.functional as tf +import librosa.filters as filters + +from typing import Optional, Tuple +from distutils.version import LooseVersion + +EPSILON = float(np.finfo(np.float32).eps) +TORCH_VERSION = th.__version__ + +if TORCH_VERSION >= LooseVersion("1.7"): + from torch.fft import fft as fft_func +else: + pass + + +def export_jit(transform: nn.Module) -> nn.Module: + """ + Export transform module for inference + """ + export_out = [module for module in transform if module.exportable()] + return nn.Sequential(*export_out) + + +def init_window(wnd: str, frame_len: int, device: th.device = "cpu") -> th.Tensor: + """ + Return window coefficient + Args: + wnd: window name + frame_len: length of the frame + """ + + def sqrthann(frame_len, periodic=True): + return th.hann_window(frame_len, periodic=periodic) ** 0.5 + + if wnd not in ["bartlett", "hann", "hamm", "blackman", "rect", "sqrthann"]: + raise RuntimeError(f"Unknown window type: {wnd}") + + wnd_tpl = { + "sqrthann": sqrthann, + "hann": th.hann_window, + "hamm": th.hamming_window, + "blackman": th.blackman_window, + "bartlett": th.bartlett_window, + "rect": th.ones, + } + if wnd != "rect": + # match with librosa + c = wnd_tpl[wnd](frame_len, periodic=True) + else: + c = wnd_tpl[wnd](frame_len) + return c.to(device) + + +def init_kernel( + frame_len: int, + frame_hop: int, + window: th.Tensor, + round_pow_of_two: bool = True, + normalized: bool = False, + inverse: bool = False, + mode: str = "librosa", +) -> Tuple[th.Tensor, th.Tensor]: + """ + Return STFT kernels + Args: + frame_len: length of the frame + frame_hop: hop size between frames + window: window tensor + round_pow_of_two: if true, choose round(#power_of_two) as the FFT size + normalized: return normalized DFT matrix + inverse: return iDFT matrix + mode: framing mode (librosa or kaldi) + """ + if mode not in ["librosa", "kaldi"]: + raise ValueError(f"Unsupported mode: {mode}") + # FFT size: B + if round_pow_of_two or mode == "kaldi": + fft_size = 2 ** math.ceil(math.log2(frame_len)) + else: + fft_size = frame_len + # center padding window if needed + if mode == "librosa" and fft_size != frame_len: + lpad = (fft_size - frame_len) // 2 + window = tf.pad(window, (lpad, fft_size - frame_len - lpad)) + if normalized: + # make K^H * K = I + S = fft_size ** 0.5 + else: + S = 1 + # W x B x 2 + if TORCH_VERSION >= LooseVersion("1.7"): + K = fft_func(th.eye(fft_size) / S, dim=-1) + K = th.stack([K.real, K.imag], dim=-1) + else: + I = th.stack([th.eye(fft_size), th.zeros(fft_size, fft_size)], dim=-1) + K = th.fft(I / S, 1) + if mode == "kaldi": + K = K[:frame_len] + if inverse and not normalized: + # to make K^H * K = I + K = K / fft_size + # 2 x B x W + K = th.transpose(K, 0, 2) + # 2B x 1 x W + K = th.reshape(K, (fft_size * 2, 1, K.shape[-1])) + return K.to(window.device), window + + +def mel_filter( + frame_len: int, + round_pow_of_two: bool = True, + num_bins: Optional[int] = None, + sr: int = 16000, + num_mels: int = 80, + fmin: float = 0.0, + fmax: Optional[float] = None, + norm: bool = False, +) -> th.Tensor: + """ + Return mel filter coefficients + Args: + frame_len: length of the frame + round_pow_of_two: if true, choose round(#power_of_two) as the FFT size + num_bins: number of the frequency bins produced by STFT + num_mels: number of the mel bands + fmin: lowest frequency (in Hz) + fmax: highest frequency (in Hz) + norm: normalize the mel filter coefficients + """ + # FFT points + if num_bins is None: + N = 2 ** math.ceil(math.log2(frame_len)) if round_pow_of_two else frame_len + else: + N = (num_bins - 1) * 2 + # fmin & fmax + freq_upper = sr // 2 + if fmax is None: + fmax = freq_upper + else: + fmax = min(fmax + freq_upper if fmax < 0 else fmax, freq_upper) + fmin = max(0, fmin) + # mel filter coefficients + mel = filters.mel( + sr, + N, + n_mels=num_mels, + fmax=fmax, + fmin=fmin, + htk=True, + norm="slaney" if norm else None, + ) + # num_mels x (N // 2 + 1) + return th.tensor(mel, dtype=th.float32) + + +def speed_perturb_filter( + src_sr: int, dst_sr: int, cutoff_ratio: float = 0.95, num_zeros: int = 64 +) -> th.Tensor: + """ + Return speed perturb filters, reference: + https://github.com/danpovey/filtering/blob/master/lilfilter/resampler.py + Args: + src_sr: sample rate of the source signal + dst_sr: sample rate of the target signal + Return: + weight (Tensor): coefficients of the filter + """ + if src_sr == dst_sr: + raise ValueError(f"src_sr should not be equal to dst_sr: {src_sr}/{dst_sr}") + gcd = math.gcd(src_sr, dst_sr) + src_sr = src_sr // gcd + dst_sr = dst_sr // gcd + if src_sr == 1 or dst_sr == 1: + raise ValueError("do not support integer downsample/upsample") + zeros_per_block = min(src_sr, dst_sr) * cutoff_ratio + padding = 1 + int(num_zeros / zeros_per_block) + # dst_sr x src_sr x K + times = ( + np.arange(dst_sr)[:, None, None] / float(dst_sr) + - np.arange(src_sr)[None, :, None] / float(src_sr) + - np.arange(2 * padding + 1)[None, None, :] + + padding + ) + window = np.heaviside(1 - np.abs(times / padding), 0.0) * ( + 0.5 + 0.5 * np.cos(times / padding * math.pi) + ) + weight = np.sinc(times * zeros_per_block) * window * zeros_per_block / float(src_sr) + return th.tensor(weight, dtype=th.float32) + + +def splice_feature( + feats: th.Tensor, lctx: int = 1, rctx: int = 1, op: str = "cat" +) -> th.Tensor: + """ + Splice feature + Args: + feats (Tensor): N x ... x T x F, original feature + lctx: left context + rctx: right context + op: operator on feature context + Return: + splice (Tensor): feature with context padded + """ + if lctx + rctx == 0: + return feats + if op not in ["cat", "stack"]: + raise ValueError(f"Unknown op for feature splicing: {op}") + # [N x ... x T x F, ...] + ctx = [] + T = feats.shape[-2] + for c in range(-lctx, rctx + 1): + idx = th.arange(c, c + T, device=feats.device, dtype=th.int64) + idx = th.clamp(idx, min=0, max=T - 1) + ctx.append(th.index_select(feats, -2, idx)) + if op == "cat": + # N x ... x T x FD + splice = th.cat(ctx, -1) + else: + # N x ... x T x F x D + splice = th.stack(ctx, -1) + return splice + + +def _forward_stft( + wav: th.Tensor, + kernel: th.Tensor, + window: th.Tensor, + return_polar: bool = False, + pre_emphasis: float = 0, + frame_hop: int = 256, + onesided: bool = False, + center: bool = False, + eps: float = EPSILON, +) -> th.Tensor: + """ + STFT function implemented by conv1d (not efficient, but we don't care during training) + Args: + wav (Tensor): N x (C) x S + kernel (Tensor): STFT transform kernels, from init_kernel(...) + return_polar: return [magnitude; phase] Tensor or [real; imag] Tensor + pre_emphasis: factor of preemphasis + frame_hop: frame hop size in number samples + onesided: return half FFT bins + center: if true, we assumed to have centered frames + Return: + transform (Tensor): STFT transform results + """ + wav_dim = wav.dim() + if wav_dim not in [2, 3]: + raise RuntimeError(f"STFT expect 2D/3D tensor, but got {wav_dim:d}D") + # if N x S, reshape N x 1 x S + # else: reshape NC x 1 x S + N, S = wav.shape[0], wav.shape[-1] + wav = wav.view(-1, 1, S) + # NC x 1 x S+2P + if center: + pad = kernel.shape[-1] // 2 + # NOTE: match with librosa + wav = tf.pad(wav, (pad, pad), mode="reflect") + # STFT + kernel = kernel * window + if pre_emphasis > 0: + # NC x W x T + frames = tf.unfold( + wav[:, None], (1, kernel.shape[-1]), stride=frame_hop, padding=0 + ) + # follow Kaldi's Preemphasize + frames[:, 1:] = frames[:, 1:] - pre_emphasis * frames[:, :-1] + frames[:, 0] *= 1 - pre_emphasis + # 1 x 2B x W, NC x W x T, NC x 2B x T + packed = th.matmul(kernel[:, 0][None, ...], frames) + else: + packed = tf.conv1d(wav, kernel, stride=frame_hop, padding=0) + # NC x 2B x T => N x C x 2B x T + if wav_dim == 3: + packed = packed.view(N, -1, packed.shape[-2], packed.shape[-1]) + # N x (C) x B x T + real, imag = th.chunk(packed, 2, dim=-2) + # N x (C) x B/2+1 x T + if onesided: + num_bins = kernel.shape[0] // 4 + 1 + real = real[..., :num_bins, :] + imag = imag[..., :num_bins, :] + if return_polar: + mag = (real ** 2 + imag ** 2 + eps) ** 0.5 + pha = th.atan2(imag, real) + return th.stack([mag, pha], dim=-1) + else: + return th.stack([real, imag], dim=-1) + + +def _inverse_stft( + transform: th.Tensor, + kernel: th.Tensor, + window: th.Tensor, + return_polar: bool = False, + frame_hop: int = 256, + onesided: bool = False, + center: bool = False, + eps: float = EPSILON, +) -> th.Tensor: + """ + iSTFT function implemented by conv1d + Args: + transform (Tensor): STFT transform results + kernel (Tensor): STFT transform kernels, from init_kernel(...) + return_polar (bool): keep same with the one in _forward_stft + frame_hop: frame hop size in number samples + onesided: return half FFT bins + center: used in _forward_stft + Return: + wav (Tensor), N x S + """ + # (N) x F x T x 2 + transform_dim = transform.dim() + # if F x T x 2, reshape 1 x F x T x 2 + if transform_dim == 3: + transform = th.unsqueeze(transform, 0) + if transform_dim != 4: + raise RuntimeError(f"Expect 4D tensor, but got {transform_dim}D") + + if return_polar: + real = transform[..., 0] * th.cos(transform[..., 1]) + imag = transform[..., 0] * th.sin(transform[..., 1]) + else: + real, imag = transform[..., 0], transform[..., 1] + + if onesided: + # [self.num_bins - 2, ..., 1] + reverse = range(kernel.shape[0] // 4 - 1, 0, -1) + # extend matrix: N x B x T + real = th.cat([real, real[:, reverse]], 1) + imag = th.cat([imag, -imag[:, reverse]], 1) + # pack: N x 2B x T + packed = th.cat([real, imag], dim=1) + # N x 1 x T + wav = tf.conv_transpose1d(packed, kernel * window, stride=frame_hop, padding=0) + # normalized audio samples + # refer: https://github.com/pytorch/audio/blob/2ebbbf511fb1e6c47b59fd32ad7e66023fa0dff1/torchaudio/functional.py#L171 + num_frames = packed.shape[-1] + win_length = window.shape[0] + # W x T + win = th.repeat_interleave(window[..., None] ** 2, num_frames, dim=-1) + # Do OLA on windows + # v1) + I = th.eye(win_length, device=win.device)[:, None] + denorm = tf.conv_transpose1d(win[None, ...], I, stride=frame_hop, padding=0) + # v2) + # num_samples = (num_frames - 1) * frame_hop + win_length + # denorm = tf.fold(win[None, ...], (num_samples, 1), (win_length, 1), + # stride=frame_hop)[..., 0] + if center: + pad = kernel.shape[-1] // 2 + wav = wav[..., pad:-pad] + denorm = denorm[..., pad:-pad] + wav = wav / (denorm + eps) + # N x S + return wav.squeeze(1) + + +def _pytorch_stft( + wav: th.Tensor, + frame_len: int, + frame_hop: int, + n_fft: int = 512, + return_polar: bool = False, + window: str = "sqrthann", + normalized: bool = False, + onesided: bool = True, + center: bool = False, + eps: float = EPSILON, +) -> th.Tensor: + """ + Wrapper of PyTorch STFT function + Args: + wav (Tensor): source audio signal + frame_len: length of the frame + frame_hop: hop size between frames + n_fft: number of the FFT size + return_polar: return the results in polar coordinate + window: window tensor + center: same definition with the parameter in librosa.stft + normalized: use normalized DFT kernel + onesided: output onesided STFT + Return: + transform (Tensor), STFT transform results + """ + if TORCH_VERSION < LooseVersion("1.7"): + raise RuntimeError("Can not use this function as TORCH_VERSION < 1.7") + wav_dim = wav.dim() + if wav_dim not in [2, 3]: + raise RuntimeError(f"STFT expect 2D/3D tensor, but got {wav_dim:d}D") + # if N x C x S, reshape NC x S + wav = wav.view(-1, wav.shape[-1]) + # STFT: N x F x T x 2 + stft = th.stft( + wav, + n_fft, + hop_length=frame_hop, + win_length=window.shape[-1], + window=window, + center=center, + normalized=normalized, + onesided=onesided, + return_complex=False, + ) + if wav_dim == 3: + N, F, T, _ = stft.shape + stft = stft.view(N, -1, F, T, 2) + # N x (C) x F x T x 2 + if not return_polar: + return stft + # N x (C) x F x T + real, imag = stft[..., 0], stft[..., 1] + mag = (real ** 2 + imag ** 2 + eps) ** 0.5 + pha = th.atan2(imag, real) + return th.stack([mag, pha], dim=-1) + + +def _pytorch_istft( + transform: th.Tensor, + frame_len: int, + frame_hop: int, + window: th.Tensor, + n_fft: int = 512, + return_polar: bool = False, + normalized: bool = False, + onesided: bool = True, + center: bool = False, + eps: float = EPSILON, +) -> th.Tensor: + """ + Wrapper of PyTorch iSTFT function + Args: + transform (Tensor): results of STFT + frame_len: length of the frame + frame_hop: hop size between frames + window: window tensor + n_fft: number of the FFT size + return_polar: keep same with _pytorch_stft + center: same definition with the parameter in librosa.stft + normalized: use normalized DFT kernel + onesided: output onesided STFT + Return: + wav (Tensor): synthetic audio + """ + if TORCH_VERSION < LooseVersion("1.7"): + raise RuntimeError("Can not use this function as TORCH_VERSION < 1.7") + + transform_dim = transform.dim() + # if F x T x 2, reshape 1 x F x T x 2 + if transform_dim == 3: + transform = th.unsqueeze(transform, 0) + if transform_dim != 4: + raise RuntimeError(f"Expect 4D tensor, but got {transform_dim}D") + + if return_polar: + real = transform[..., 0] * th.cos(transform[..., 1]) + imag = transform[..., 0] * th.sin(transform[..., 1]) + transform = th.stack([real, imag], -1) + # stft is a complex tensor of PyTorch + stft = th.view_as_complex(transform) + # (N) x S + wav = th.istft( + stft, + n_fft, + hop_length=frame_hop, + win_length=window.shape[-1], + window=window, + center=center, + normalized=normalized, + onesided=onesided, + return_complex=False, + ) + return wav + + +def forward_stft( + wav: th.Tensor, + frame_len: int, + frame_hop: int, + window: str = "sqrthann", + round_pow_of_two: bool = True, + return_polar: bool = False, + pre_emphasis: float = 0, + normalized: bool = False, + onesided: bool = True, + center: bool = False, + mode: str = "librosa", + eps: float = EPSILON, +) -> th.Tensor: + """ + STFT function implementation, equals to STFT layer + Args: + wav: source audio signal + frame_len: length of the frame + frame_hop: hop size between frames + return_polar: return [magnitude; phase] Tensor or [real; imag] Tensor + window: window name + center: center flag (similar with that in librosa.stft) + round_pow_of_two: if true, choose round(#power_of_two) as the FFT size + pre_emphasis: factor of preemphasis + normalized: use normalized DFT kernel + onesided: output onesided STFT + inverse: using iDFT kernel (for iSTFT) + mode: STFT mode, "kaldi" or "librosa" or "torch" + Return: + transform: results of STFT + """ + window = init_window(window, frame_len, device=wav.device) + if mode == "torch": + n_fft = 2 ** math.ceil(math.log2(frame_len)) if round_pow_of_two else frame_len + return _pytorch_stft( + wav, + frame_len, + frame_hop, + n_fft=n_fft, + return_polar=return_polar, + window=window, + normalized=normalized, + onesided=onesided, + center=center, + eps=eps, + ) + else: + kernel, window = init_kernel( + frame_len, + frame_hop, + window=window, + round_pow_of_two=round_pow_of_two, + normalized=normalized, + inverse=False, + mode=mode, + ) + return _forward_stft( + wav, + kernel, + window, + return_polar=return_polar, + frame_hop=frame_hop, + pre_emphasis=pre_emphasis, + onesided=onesided, + center=center, + eps=eps, + ) + + +def inverse_stft( + transform: th.Tensor, + frame_len: int, + frame_hop: int, + return_polar: bool = False, + window: str = "sqrthann", + round_pow_of_two: bool = True, + normalized: bool = False, + onesided: bool = True, + center: bool = False, + mode: str = "librosa", + eps: float = EPSILON, +) -> th.Tensor: + """ + iSTFT function implementation, equals to iSTFT layer + Args: + transform: results of STFT + frame_len: length of the frame + frame_hop: hop size between frames + return_polar: keep same with function forward_stft(...) + window: window name + center: center flag (similar with that in librosa.stft) + round_pow_of_two: if true, choose round(#power_of_two) as the FFT size + normalized: use normalized DFT kernel + onesided: output onesided STFT + mode: STFT mode, "kaldi" or "librosa" or "torch" + Return: + wav: synthetic signals + """ + window = init_window(window, frame_len, device=transform.device) + if mode == "torch": + n_fft = 2 ** math.ceil(math.log2(frame_len)) if round_pow_of_two else frame_len + return _pytorch_istft( + transform, + frame_len, + frame_hop, + n_fft=n_fft, + return_polar=return_polar, + window=window, + normalized=normalized, + onesided=onesided, + center=center, + eps=eps, + ) + else: + kernel, window = init_kernel( + frame_len, + frame_hop, + window, + round_pow_of_two=round_pow_of_two, + normalized=normalized, + inverse=True, + mode=mode, + ) + return _inverse_stft( + transform, + kernel, + window, + return_polar=return_polar, + frame_hop=frame_hop, + onesided=onesided, + center=center, + eps=eps, + ) + + +class STFTBase(nn.Module): + """ + Base layer for (i)STFT + Args: + frame_len: length of the frame + frame_hop: hop size between frames + window: window name + center: center flag (similar with that in librosa.stft) + round_pow_of_two: if true, choose round(#power_of_two) as the FFT size + normalized: use normalized DFT kernel + pre_emphasis: factor of preemphasis + mode: STFT mode, "kaldi" or "librosa" or "torch" + onesided: output onesided STFT + inverse: using iDFT kernel (for iSTFT) + """ + + def __init__( + self, + frame_len: int, + frame_hop: int, + window: str = "sqrthann", + round_pow_of_two: bool = True, + normalized: bool = False, + pre_emphasis: float = 0, + onesided: bool = True, + inverse: bool = False, + center: bool = False, + mode: str = "librosa", + ) -> None: + super(STFTBase, self).__init__() + if mode != "torch": + K, w = init_kernel( + frame_len, + frame_hop, + init_window(window, frame_len), + round_pow_of_two=round_pow_of_two, + normalized=normalized, + inverse=inverse, + mode=mode, + ) + self.K = nn.Parameter(K, requires_grad=False) + self.w = nn.Parameter(w, requires_grad=False) + self.num_bins = self.K.shape[0] // 4 + 1 + self.pre_emphasis = pre_emphasis + self.win_length = self.K.shape[2] + else: + self.K = None + w = init_window(window, frame_len) + self.w = nn.Parameter(w, requires_grad=False) + fft_size = ( + 2 ** math.ceil(math.log2(frame_len)) if round_pow_of_two else frame_len + ) + self.num_bins = fft_size // 2 + 1 + self.pre_emphasis = 0 + self.win_length = fft_size + self.frame_len = frame_len + self.frame_hop = frame_hop + self.window = window + self.normalized = normalized + self.onesided = onesided + self.center = center + self.mode = mode + + def num_frames(self, wav_len: th.Tensor) -> th.Tensor: + """ + Compute number of the frames + """ + assert th.sum(wav_len <= self.win_length) == 0 + if self.center: + wav_len += self.win_length + return ( + th.div(wav_len - self.win_length, self.frame_hop, rounding_mode="trunc") + 1 + ) + + def extra_repr(self) -> str: + str_repr = ( + f"num_bins={self.num_bins}, win_length={self.win_length}, " + + f"stride={self.frame_hop}, window={self.window}, " + + f"center={self.center}, mode={self.mode}" + ) + if not self.onesided: + str_repr += f", onesided={self.onesided}" + if self.pre_emphasis > 0: + str_repr += f", pre_emphasis={self.pre_emphasis}" + if self.normalized: + str_repr += f", normalized={self.normalized}" + return str_repr + + +class STFT(STFTBase): + """ + Short-time Fourier Transform as a Layer + """ + + def __init__(self, *args, **kwargs): + super(STFT, self).__init__(*args, inverse=False, **kwargs) + + def forward( + self, wav: th.Tensor, return_polar: bool = False, eps: float = EPSILON + ) -> th.Tensor: + """ + Accept (single or multiple channel) raw waveform and output magnitude and phase + Args + wav (Tensor) input signal, N x (C) x S + Return + transform (Tensor), N x (C) x F x T x 2 + """ + if self.mode == "torch": + return _pytorch_stft( + wav, + self.frame_len, + self.frame_hop, + n_fft=(self.num_bins - 1) * 2, + return_polar=return_polar, + window=self.w, + normalized=self.normalized, + onesided=self.onesided, + center=self.center, + eps=eps, + ) + else: + return _forward_stft( + wav, + self.K, + self.w, + return_polar=return_polar, + frame_hop=self.frame_hop, + pre_emphasis=self.pre_emphasis, + onesided=self.onesided, + center=self.center, + eps=eps, + ) + + +class iSTFT(STFTBase): + """ + Inverse Short-time Fourier Transform as a Layer + """ + + def __init__(self, *args, **kwargs): + super(iSTFT, self).__init__(*args, inverse=True, **kwargs) + + def forward( + self, transform: th.Tensor, return_polar: bool = False, eps: float = EPSILON + ) -> th.Tensor: + """ + Accept phase & magnitude and output raw waveform + Args + transform (Tensor): STFT output, N x F x T x 2 + Return + s (Tensor): N x S + """ + if self.mode == "torch": + return _pytorch_istft( + transform, + self.frame_len, + self.frame_hop, + n_fft=(self.num_bins - 1) * 2, + return_polar=return_polar, + window=self.w, + normalized=self.normalized, + onesided=self.onesided, + center=self.center, + eps=eps, + ) + else: + return _inverse_stft( + transform, + self.K, + self.w, + return_polar=return_polar, + frame_hop=self.frame_hop, + onesided=self.onesided, + center=self.center, + eps=eps, + ) diff --git a/look2hear/utils/torch_utils.py b/look2hear/utils/torch_utils.py new file mode 100644 index 0000000..7c7cc70 --- /dev/null +++ b/look2hear/utils/torch_utils.py @@ -0,0 +1,49 @@ +### +# Author: Kai Li +# Date: 2021-06-18 17:29:21 +# LastEditors: Kai Li +# LastEditTime: 2021-06-21 23:52:52 +### + +import torch +import torch.nn as nn + + +def pad_x_to_y(x, y, axis: int = -1): + if axis != -1: + raise NotImplementedError + inp_len = y.shape[axis] + output_len = x.shape[axis] + return nn.functional.pad(x, [0, inp_len - output_len]) + + +def shape_reconstructed(reconstructed, size): + if len(size) == 1: + return reconstructed.squeeze(0) + return reconstructed + + +def tensors_to_device(tensors, device): + """Transfer tensor, dict or list of tensors to device. + + Args: + tensors (:class:`torch.Tensor`): May be a single, a list or a + dictionary of tensors. + device (:class: `torch.device`): the device where to place the tensors. + + Returns: + Union [:class:`torch.Tensor`, list, tuple, dict]: + Same as input but transferred to device. + Goes through lists and dicts and transfers the torch.Tensor to + device. Leaves the rest untouched. + """ + if isinstance(tensors, torch.Tensor): + return tensors.to(device) + elif isinstance(tensors, (list, tuple)): + return [tensors_to_device(tens, device) for tens in tensors] + elif isinstance(tensors, dict): + for key in tensors.keys(): + tensors[key] = tensors_to_device(tensors[key], device) + return tensors + else: + return tensors -- cgit v1.2.3