File size: 8,293 Bytes
df9f13e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
import os
import glob
import importlib
import json
import librosa
import soundfile as sf
import torch
import torchaudio
import math
import torch.nn as nn
class PositionalEncoding(nn.Module):
"""This class implements the absolute sinusoidal positional encoding function.
PE(pos, 2i) = sin(pos/(10000^(2i/dmodel)))
PE(pos, 2i+1) = cos(pos/(10000^(2i/dmodel)))
Arguments
---------
input_size: int
Embedding dimension.
max_len : int, optional
Max length of the input sequences (default 2500).
Example
-------
>>> a = torch.rand((8, 120, 512))
>>> enc = PositionalEncoding(input_size=a.shape[-1])
>>> b = enc(a)
>>> b.shape
torch.Size([1, 120, 512])
"""
def __init__(self, input_size, max_len=2500):
super().__init__()
if input_size % 2 != 0:
raise ValueError(f"Cannot use sin/cos positional encoding with odd channels (got channels={input_size})")
self.max_len = max_len
pe = torch.zeros(self.max_len, input_size, requires_grad=False)
positions = torch.arange(0, self.max_len).unsqueeze(1).float()
denominator = torch.exp(torch.arange(0, input_size, 2).float() * -(math.log(10000.0) / input_size))
pe[:, 0::2] = torch.sin(positions * denominator)
pe[:, 1::2] = torch.cos(positions * denominator)
pe = pe.unsqueeze(0)
self.register_buffer("pe", pe)
def forward(self, x):
"""
Arguments
---------
x : tensor
Input feature shape (batch, time, fea)
"""
return self.pe[:, : x.size(1)].clone().detach()
def count_parameters(model):
"""
Count the number of parameters in a PyTorch model.
Parameters:
model (torch.nn.Module): The PyTorch model.
Returns:
int: Number of parameters in the model.
"""
N_param = sum(p.numel() for p in model.parameters())
print(f"Model params number {N_param/1e6} M")
def import_attr(import_path):
module, attr = import_path.rsplit(".", 1)
return getattr(importlib.import_module(module), attr)
class Params:
"""Class that loads hyperparameters from a json file.
Example:
```
params = Params(json_path)
print(params.learning_rate)
params.learning_rate = 0.5 # change the value of learning_rate in params
```
"""
def __init__(self, json_path):
with open(json_path) as f:
params = json.load(f)
self.__dict__.update(params)
def save(self, json_path):
with open(json_path, "w") as f:
json.dump(self.__dict__, f, indent=4)
def update(self, json_path):
"""Loads parameters from json file"""
with open(json_path) as f:
params = json.load(f)
self.__dict__.update(params)
@property
def dict(self):
"""Gives dict-like access to Params instance by `params.dict['learning_rate']"""
return self.__dict__
def load_net_torch(expriment_config, return_params=False):
params = Params(expriment_config)
params.pl_module_args["slow_model_ckpt"] = None
params.pl_module_args["use_dp"] = False
params.pl_module_args["prev_ckpt"] = None
pl_module = import_attr(params.pl_module)(**params.pl_module_args)
with open(expriment_config) as f:
params = json.load(f)
if return_params:
return pl_module, params
else:
return pl_module
def load_net(expriment_config, return_params=False):
params = Params(expriment_config)
params.pl_module_args["use_dp"] = False
pl_module = import_attr(params.pl_module)(**params.pl_module_args)
with open(expriment_config) as f:
params = json.load(f)
if return_params:
return pl_module, params
else:
return pl_module
def load_pretrained(run_dir, return_params=False, map_location="cpu", use_last=False):
config_path = os.path.join(run_dir, "config.json")
pl_module, params = load_net(config_path, return_params=True)
# Get all "best" checkpoints
if use_last:
name = "last.pt"
else:
name = "best.pt"
ckpt_path = os.path.join(run_dir, f"checkpoints/{name}")
if not os.path.exists(ckpt_path):
raise FileNotFoundError(f"Given run ({run_dir}) doesn't have any pretrained checkpoints!")
print("Loading checkpoint from", ckpt_path)
# Load checkpoint
# state_dict = torch.load(ckpt_path, map_location=map_location)['state_dict']
pl_module.load_state(ckpt_path, map_location)
print("Loaded module at epoch", pl_module.epoch)
if return_params:
return pl_module, params
else:
return pl_module
def load_pretrained_with_last(run_dir, return_params=False, map_location="cpu", use_last=False):
config_path = os.path.join(run_dir, "config.json")
pl_module, params = load_net(config_path, return_params=True)
# Get all "best" checkpoints
if use_last:
name = "last.pt"
else:
name = "best.pt"
ckpt_path = os.path.join(run_dir, f"checkpoints/{name}")
if not os.path.exists(ckpt_path):
raise FileNotFoundError(f"Given run ({run_dir}) doesn't have any pretrained checkpoints!")
print("Loading checkpoint from", ckpt_path)
# Load checkpoint
# state_dict = torch.load(ckpt_path, map_location=map_location)['state_dict']
pl_module.load_state(ckpt_path, map_location)
print("Loaded module at epoch", pl_module.epoch)
if return_params:
return pl_module, params
else:
return pl_module
def load_pretrained2(run_dir, return_params=False, map_location="cpu"):
config_path = os.path.join(run_dir, "config.json")
pl_module, params = load_net(config_path, return_params=True)
ckpt_path = os.path.join(run_dir, "checkpoints", "best.pt")
print("Loading checkpoint from", ckpt_path)
# Load checkpoint
# state_dict = torch.load(ckpt_path, map_location=map_location)['state_dict']
pl_module.load_state(ckpt_path)
if return_params:
return pl_module, params
else:
return pl_module
def load_torch_pretrained(run_dir, return_params=False, map_location="cpu", model_epoch="best"):
config_path = os.path.join(run_dir, "config.json")
print(config_path)
pl_module, params = load_net_torch(config_path, return_params=True)
# Get all "best" checkpoints
ckpt_path = os.path.join(run_dir, f"checkpoints/{model_epoch}.pt")
if not os.path.exists(ckpt_path):
raise FileNotFoundError(f"Given run ({run_dir}) doesn't have any pretrained checkpoints!")
print("Loading checkpoint from", ckpt_path)
# Load checkpoint
# state_dict = torch.load(ckpt_path, map_location=map_location)['state_dict']
pl_module.load_state(ckpt_path, map_location)
print("Loaded module at epoch", pl_module.epoch)
if return_params:
return pl_module, params
else:
return pl_module
def read_audio_file(file_path, sr):
"""
Reads audio file to system memory.
"""
return librosa.core.load(file_path, mono=False, sr=sr)[0]
def read_audio_file_torch(file_path, downsample=1, input_mean=False):
waveform, sample_rate = torchaudio.load(file_path)
if downsample > 1:
waveform = torchaudio.functional.resample(waveform, sample_rate, sample_rate // downsample)
if waveform.shape[0] > 1 and input_mean == True:
waveform = torch.mean(waveform, dim=0)
waveform = waveform.unsqueeze(0)
elif waveform.shape[0] > 1 and input_mean == "L":
waveform = waveform[0:1, ...]
elif waveform.shape[0] > 1 and input_mean == "R":
waveform = waveform[1:2, ...]
return waveform
def write_audio_file(file_path, data, sr, subtype="PCM_16"):
"""
Writes audio file to system memory.
@param file_path: Path of the file to write to
@param data: Audio signal to write (n_channels x n_samples)
@param sr: Sampling rate
"""
sf.write(file_path, data.T, sr, subtype)
def read_json(path):
with open(path, "rb") as f:
return json.load(f)
import random
import numpy as np
def seed_all(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
|