Skip to content

Instantly share code, notes, and snippets.

@tam17aki
Created November 22, 2022 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tam17aki/f58416b803e96c90b4cc4fb9b3af113b to your computer and use it in GitHub Desktop.
Save tam17aki/f58416b803e96c90b4cc4fb9b3af113b to your computer and use it in GitHub Desktop.
Training script for Sinusoidal Frequency Estimation by Gradient Descent
# -*- coding: utf-8 -*-
"""Training script for Sinusoidal Frequency Estimation by Gradient Descent.
Copyright (C) 2022 by Akira TAMAMORI
Copyright (C) 2022 by @xiao_ming
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import os
import librosa
import numpy as np
import pysptk
import soundfile as sf
import torch
from hydra import compose, initialize
from progressbar import progressbar
from torch import nn
class SFE(nn.Module):
"""Sinusoidal Frequency Estimation (SFE) class."""
def __init__(self, batch_size, cfg, device):
"""Initialize class."""
super().__init__()
n_sines = cfg.model.n_sines
init_freq = torch.rand(batch_size, n_sines, 1) * torch.pi
init_phase = torch.rand(batch_size, n_sines, 1) * torch.pi
self._omega = nn.Parameter(torch.exp(init_freq * 1.0j))
self._phi = nn.Parameter(torch.exp(init_phase * 1.0j))
self.n_sines = n_sines
self.arr_n = torch.arange(cfg.feature.frame_length).to(device)
self.criterion = nn.MSELoss()
self.config = cfg
def forward(self):
"""Perform forward propagation."""
mag = self._omega.abs().pow(self.arr_n) * self._phi.abs()
sinusoid = torch.cos(self._omega.angle() * self.arr_n + self._phi.angle())
estimated = mag * sinusoid
estimated = torch.sum(estimated, dim=1) # [B, T]
return estimated
def get_loss(self, target):
"""Return MSE loss."""
estimated_sinusoid = self.forward()
loss = self.criterion(estimated_sinusoid, target)
return loss
@property
def omega(self):
"""Get omega."""
return self._omega
@property
def phi(self):
"""Get phi."""
return self._phi
def training_loop(target, model, cfg):
"""Perform training loop."""
optimizer = torch.optim.Adam(
[model.omega, model.phi], lr=cfg.training.learning_rate
)
train_loss = 0.0
for _ in progressbar(range(1, cfg.training.n_epochs)):
optimizer.zero_grad()
loss = model.get_loss(target)
loss.backward()
optimizer.step()
train_loss += loss.item()
train_loss /= cfg.training.n_epochs
print(f"Loss: {train_loss}")
return train_loss
def overlap_add(framed, cfg):
"""Perform overlap-add to reconstruct whole waveform."""
frame_length = config.feature.frame_length
framed = framed.reshape(-1, frame_length)
framed *= pysptk.hanning(frame_length)
n_frame = framed.shape[0]
half = int(frame_length / 2)
output = np.zeros(n_frame * half)
for i in range(n_frame):
if i > 0:
output[i * half : (i + 1) * half] = (
framed[i - 1, half:frame_length] + framed[i, :half]
)
else:
output[i * half : (i + 1) * half] = framed[0, :half]
output = output / np.max(np.abs(output))
output *= 2 ** (2 * 8 - 1) - 1 # 16bit
output = output.astype(np.int16)
return output
def main(wav_file, cfg):
"""Perform model training."""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# load target waveform
wav_file = os.path.join(os.path.join(cfg.SFE.root_dir, cfg.SFE.data_dir), wav_file)
audio, _ = librosa.load(wav_file, sr=cfg.feature.sample_rate)
audio, _ = librosa.effects.trim(audio)
frames = librosa.util.frame(
audio, frame_length=cfg.feature.frame_length, hop_length=cfg.feature.hop_length
).T
target = torch.from_numpy(frames.astype(np.float32)).clone().to(device)
# split target into batches
target_batch = torch.split(target, cfg.training.n_batchs)
# perform training
output = []
for tgt in target_batch:
model = SFE(tgt.shape[0], cfg, device).to(device)
training_loop(tgt, model, cfg)
estimated = model.forward()
estimated = estimated.to("cpu").detach().numpy().copy()
estimated = estimated.reshape(-1, 1).squeeze()
output.append(estimated)
del model
output = np.array(np.concatenate(output))
estimated = overlap_add(output, cfg)
sf.write(cfg.demo.out_wav, estimated, cfg.feature.sample_rate, subtype="PCM_16")
if __name__ == "__main__":
with initialize(version_base=None, config_path="."):
config = compose(config_name="config")
main(config.demo.in_wav, config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment