File size: 5,931 Bytes
90cacdf
8125531
90cacdf
 
 
8125531
 
9a9a2c9
 
90cacdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6d02ea
c1b80c0
 
 
8125531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
056a44f
 
5e4e307
5682d80
8125531
 
 
d8d3e30
8125531
d8d3e30
8125531
056a44f
 
 
 
 
 
 
7d6f241
 
5e4e307
 
 
5682d80
5e4e307
5682d80
 
 
 
5e4e307
5682d80
106ab10
7fc4de1
106ab10
5e4e307
 
 
 
7d6f241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a9a2c9
7d6f241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3350b1
 
 
 
 
 
 
 
 
 
 
 
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
import logging
from typing import List, Tuple
import pytorch_lightning as pl
from omegaconf import DictConfig
from pytorch_lightning.utilities import rank_zero_only
import torch
import torchaudio
from torch import nn
import collections.abc


def get_logger(name=__name__) -> logging.Logger:
    """Initializes multi-GPU-friendly python command line logger."""

    logger = logging.getLogger(name)

    # this ensures all logging levels get marked with the rank zero decorator
    # otherwise logs would get multiplied for each GPU process in multi-GPU setup
    for level in (
        "debug",
        "info",
        "warning",
        "error",
        "exception",
        "fatal",
        "critical",
    ):
        setattr(logger, level, rank_zero_only(getattr(logger, level)))

    return logger


log = get_logger(__name__)


@rank_zero_only
def log_hyperparameters(
    config: DictConfig,
    model: pl.LightningModule,
    datamodule: pl.LightningDataModule,
    trainer: pl.Trainer,
    callbacks: List[pl.Callback],
    logger: pl.loggers.logger.Logger,
) -> None:
    """Controls which config parts are saved by Lightning loggers.
    Additionaly saves:
    - number of model parameters
    """

    if not trainer.logger:
        return

    hparams = {}

    # choose which parts of hydra config will be saved to loggers
    hparams["model"] = config["model"]

    # save number of model parameters
    hparams["model/params/total"] = sum(p.numel() for p in model.parameters())
    hparams["model/params/trainable"] = sum(
        p.numel() for p in model.parameters() if p.requires_grad
    )
    hparams["model/params/non_trainable"] = sum(
        p.numel() for p in model.parameters() if not p.requires_grad
    )

    hparams["datamodule"] = config["datamodule"]
    hparams["trainer"] = config["trainer"]

    if "seed" in config:
        hparams["seed"] = config["seed"]
    if "callbacks" in config:
        hparams["callbacks"] = config["callbacks"]

    if isinstance(logger, pl.loggers.CSVLogger):
        logger.log_hyperparams(hparams)
    else:
        logger.experiment.config.update(hparams)


def create_random_chunks(
    audio_file: str, chunk_size: int, num_chunks: int
) -> Tuple[List[Tuple[int, int]], int]:
    """Create num_chunks random chunks of size chunk_size (seconds)
    from an audio file.
    Return sample_index of start of each chunk and original sr
    """
    audio, sr = torchaudio.load(audio_file)
    chunk_size_in_samples = chunk_size * sr
    if chunk_size_in_samples >= audio.shape[-1]:
        chunk_size_in_samples = audio.shape[-1] - 1
    chunks = []
    for i in range(num_chunks):
        start = torch.randint(0, audio.shape[-1] - chunk_size_in_samples, (1,)).item()
        chunks.append(start)
    return chunks, sr


def create_sequential_chunks(
    audio_file: str, chunk_size: int, sample_rate: int
) -> List[torch.Tensor]:
    """Create sequential chunks of size chunk_size from an audio file.
    Return each chunk
    """
    chunks = []
    audio, sr = torchaudio.load(audio_file)
    chunk_starts = torch.arange(0, audio.shape[-1], chunk_size)
    for start in chunk_starts:
        if start + chunk_size > audio.shape[-1]:
            break
        chunk = audio[:, start : start + chunk_size]
        resampled_chunk = torchaudio.functional.resample(chunk, sr, sample_rate)
        # Skip chunks that are too short
        if resampled_chunk.shape[-1] < chunk_size:
            continue
        chunks.append(chunk)
    return chunks


def select_random_chunk(
    audio_file: str, chunk_size: int, sample_rate: int
) -> List[torch.Tensor]:
    """Select random chunk of size chunk_size (samples) from an audio file."""
    audio, sr = torchaudio.load(audio_file)
    new_chunk_size = int(chunk_size * (sr / sample_rate))
    if new_chunk_size >= audio.shape[-1]:
        return None
    max_len = audio.shape[-1] - new_chunk_size
    random_start = torch.randint(0, max_len, (1,)).item()
    chunk = audio[:, random_start : random_start + new_chunk_size]
    # Skip if energy too low
    if torch.mean(torch.abs(chunk)) < 1e-4:
        return None
    resampled_chunk = torchaudio.functional.resample(chunk, sr, sample_rate)
    return resampled_chunk


def spectrogram(
    x: torch.Tensor,
    window: torch.Tensor,
    n_fft: int,
    hop_length: int,
    alpha: float,
) -> torch.Tensor:
    bs, chs, samp = x.size()
    x = x.view(bs * chs, -1)  # move channels onto batch dim

    X = torch.stft(
        x,
        n_fft=n_fft,
        hop_length=hop_length,
        window=window,
        return_complex=True,
    )

    # move channels back
    X = X.view(bs, chs, X.shape[-2], X.shape[-1])

    return torch.pow(X.abs() + 1e-8, alpha)


def init_layer(layer):
    """Initialize a Linear or Convolutional layer."""
    nn.init.xavier_uniform_(layer.weight)

    if hasattr(layer, "bias"):
        if layer.bias is not None:
            layer.bias.data.fill_(0.0)


def init_bn(bn):
    """Initialize a Batchnorm layer."""
    bn.bias.data.fill_(0.0)
    bn.weight.data.fill_(1.0)


def _ntuple(n: int):
    def parse(x):
        if isinstance(x, collections.abc.Iterable):
            return x
        return tuple([x] * n)

    return parse


single = _ntuple(1)


def concat_complex(a: torch.tensor, b: torch.tensor, dim: int = 1) -> torch.tensor:
    """
    Concatenate two complex tensors in same dimension concept
    :param a: complex tensor
    :param b: another complex tensor
    :param dim: target dimension
    :return: concatenated tensor
    """
    a_real, a_img = a.chunk(2, dim)
    b_real, b_img = b.chunk(2, dim)
    return torch.cat([a_real, b_real, a_img, b_img], dim=dim)


def center_crop(x, length: int):
    start = (x.shape[-1] - length) // 2
    stop = start + length
    return x[..., start:stop]


def causal_crop(x, length: int):
    stop = x.shape[-1] - 1
    start = stop - length
    return x[..., start:stop]