Spaces:
Runtime error
Runtime error
Commit ·
b84b595
0
Parent(s):
Duplicate from OlaWod/FreeVC
Browse filesCo-authored-by: Jingyi Li <OlaWod@users.noreply.huggingface.co>
Files changed (38)
- .gitattributesAdded+34
- .gitignoreAdded+2
- README.mdAdded+14
- app.pyAdded+103
- checkpoints/freevc-24.pthAdded+3
- checkpoints/freevc-s.pthAdded+3
- checkpoints/freevc.pthAdded+3
- commons.pyAdded+171
- configs/freevc-24.jsonAdded+54
- configs/freevc-s.jsonAdded+54
- configs/freevc.jsonAdded+54
- mel_processing.pyAdded+112
- models.pyAdded+351
- modules.pyAdded+342
- p225_001.wavAdded
- p226_002.wavAdded
- requirements.txtAdded+7
- speaker_encoder/__init__.pyAdded
- speaker_encoder/audio.pyAdded+107
- speaker_encoder/ckpt/pretrained_bak_5805000.ptAdded+3
- speaker_encoder/compute_embed.pyAdded+40
- speaker_encoder/config.pyAdded+45
- speaker_encoder/data_objects/__init__.pyAdded+2
- speaker_encoder/data_objects/random_cycler.pyAdded+37
- speaker_encoder/data_objects/speaker.pyAdded+40
- speaker_encoder/data_objects/speaker_batch.pyAdded+12
- speaker_encoder/data_objects/speaker_verification_dataset.pyAdded+56
- speaker_encoder/data_objects/utterance.pyAdded+26
- speaker_encoder/hparams.pyAdded+31
- speaker_encoder/inference.pyAdded+177
- speaker_encoder/model.pyAdded+135
- speaker_encoder/params_data.pyAdded+29
- speaker_encoder/params_model.pyAdded+11
- speaker_encoder/preprocess.pyAdded+285
- speaker_encoder/train.pyAdded+125
- speaker_encoder/visualizations.pyAdded+178
- speaker_encoder/voice_encoder.pyAdded+173
- utils.pyAdded+305
12345678910111213141516171819202122232425262728293031323334*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12__pycache__flagged1234567891011121314---title: FreeVCemoji: 🚀colorFrom: graycolorTo: redsdk: gradiosdk_version: 3.13.0app_file: app.pypinned: falselicense: mitduplicated_from: OlaWod/FreeVC---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import osimport torchimport librosaimport gradio as grfrom scipy.io.wavfile import writefrom transformers import WavLMModel
import utilsfrom models import SynthesizerTrnfrom mel_processing import mel_spectrogram_torchfrom speaker_encoder.voice_encoder import SpeakerEncoder
'''def get_wavlm(): os.system('gdown https://drive.google.com/uc?id=12-cB34qCTvByWT-QtOcZaqwwO21FLSqU') shutil.move('WavLM-Large.pt', 'wavlm')'''
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Loading FreeVC...")hps = utils.get_hparams_from_file("configs/freevc.json")freevc = SynthesizerTrn( hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, **hps.model).to(device)_ = freevc.eval()_ = utils.load_checkpoint("checkpoints/freevc.pth", freevc, None)smodel = SpeakerEncoder('speaker_encoder/ckpt/pretrained_bak_5805000.pt')
print("Loading FreeVC(24k)...")hps = utils.get_hparams_from_file("configs/freevc-24.json")freevc_24 = SynthesizerTrn( hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, **hps.model).to(device)_ = freevc_24.eval()_ = utils.load_checkpoint("checkpoints/freevc-24.pth", freevc_24, None)
print("Loading FreeVC-s...")hps = utils.get_hparams_from_file("configs/freevc-s.json")freevc_s = SynthesizerTrn( hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, **hps.model).to(device)_ = freevc_s.eval()_ = utils.load_checkpoint("checkpoints/freevc-s.pth", freevc_s, None)
print("Loading WavLM for content...")cmodel = WavLMModel.from_pretrained("microsoft/wavlm-large").to(device) def convert(model, src, tgt): with torch.no_grad(): # tgt wav_tgt, _ = librosa.load(tgt, sr=hps.data.sampling_rate) wav_tgt, _ = librosa.effects.trim(wav_tgt, top_db=20) if model == "FreeVC" or model == "FreeVC (24kHz)": g_tgt = smodel.embed_utterance(wav_tgt) g_tgt = torch.from_numpy(g_tgt).unsqueeze(0).to(device) else: wav_tgt = torch.from_numpy(wav_tgt).unsqueeze(0).to(device) mel_tgt = mel_spectrogram_torch( wav_tgt, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax ) # src wav_src, _ = librosa.load(src, sr=hps.data.sampling_rate) wav_src = torch.from_numpy(wav_src).unsqueeze(0).to(device) c = cmodel(wav_src).last_hidden_state.transpose(1, 2).to(device) # infer if model == "FreeVC": audio = freevc.infer(c, g=g_tgt) elif model == "FreeVC-s": audio = freevc_s.infer(c, mel=mel_tgt) else: audio = freevc_24.infer(c, g=g_tgt) audio = audio[0][0].data.cpu().float().numpy() if model == "FreeVC" or model == "FreeVC-s": write("out.wav", hps.data.sampling_rate, audio) else: write("out.wav", 24000, audio) out = "out.wav" return out model = gr.Dropdown(choices=["FreeVC", "FreeVC-s", "FreeVC (24kHz)"], value="FreeVC",type="value", label="Model") audio1 = gr.inputs.Audio(label="Source Audio", type='filepath')audio2 = gr.inputs.Audio(label="Reference Audio", type='filepath')inputs = [model, audio1, audio2]outputs = gr.outputs.Audio(label="Output Audio", type='filepath')
title = "FreeVC"description = "Gradio Demo for FreeVC: Towards High-Quality Text-Free One-Shot Voice Conversion. To use it, simply upload your audio, or click the example to load. Read more at the links below. Note: It seems that the WavLM checkpoint in HuggingFace is a little different from the one used to train FreeVC, which may degrade the performance a bit. In addition, speaker similarity can be largely affected if there are too much silence in the reference audio, so please <strong>trim</strong> it before submitting."article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2210.15418' target='_blank'>Paper</a> | <a href='https://github.com/OlaWod/FreeVC' target='_blank'>Github Repo</a></p>"
examples=[["FreeVC", 'p225_001.wav', 'p226_002.wav'], ["FreeVC-s", 'p226_002.wav', 'p225_001.wav'], ["FreeVC (24kHz)", 'p225_001.wav', 'p226_002.wav']]
gr.Interface(convert, inputs, outputs, title=title, description=description, article=article, examples=examples, enable_queue=True).launch()123version https://git-lfs.github.com/spec/v1oid sha256:7b39a86fefbc9ec6e30be8d26ee2a6aa5ffe6d235f6ab15773d01cdf348e5b20size 472644351123version https://git-lfs.github.com/spec/v1oid sha256:470dbc952896db9f49859dd479b687273e19b8800f5455bf03d1dfc3f8e605fdsize 490230998123version https://git-lfs.github.com/spec/v1oid sha256:e2cc2d047f63b80d1d6780e37611cec11a01d597560393b1fe6118158b3bd47fsize 472644351123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171import mathimport numpy as npimport torchfrom torch import nnfrom torch.nn import functional as F
def init_weights(m, mean=0.0, std=0.01): classname = m.__class__.__name__ if classname.find("Conv") != -1: m.weight.data.normal_(mean, std)
def get_padding(kernel_size, dilation=1): return int((kernel_size*dilation - dilation)/2)
def convert_pad_shape(pad_shape): l = pad_shape[::-1] pad_shape = [item for sublist in l for item in sublist] return pad_shape
def intersperse(lst, item): result = [item] * (len(lst) * 2 + 1) result[1::2] = lst return result
def kl_divergence(m_p, logs_p, m_q, logs_q): """KL(P||Q)""" kl = (logs_q - logs_p) - 0.5 kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q) return kl
def rand_gumbel(shape): """Sample from the Gumbel distribution, protect from overflows.""" uniform_samples = torch.rand(shape) * 0.99998 + 0.00001 return -torch.log(-torch.log(uniform_samples))
def rand_gumbel_like(x): g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device) return g
def slice_segments(x, ids_str, segment_size=4): ret = torch.zeros_like(x[:, :, :segment_size]) for i in range(x.size(0)): idx_str = ids_str[i] idx_end = idx_str + segment_size ret[i] = x[i, :, idx_str:idx_end] return ret
def rand_slice_segments(x, x_lengths=None, segment_size=4): b, d, t = x.size() if x_lengths is None: x_lengths = t ids_str_max = x_lengths - segment_size + 1 ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long) ret = slice_segments(x, ids_str, segment_size) return ret, ids_str
def rand_spec_segments(x, x_lengths=None, segment_size=4): b, d, t = x.size() if x_lengths is None: x_lengths = t ids_str_max = x_lengths - segment_size ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long) ret = slice_segments(x, ids_str, segment_size) return ret, ids_str
def get_timing_signal_1d( length, channels, min_timescale=1.0, max_timescale=1.0e4): position = torch.arange(length, dtype=torch.float) num_timescales = channels // 2 log_timescale_increment = ( math.log(float(max_timescale) / float(min_timescale)) / (num_timescales - 1)) inv_timescales = min_timescale * torch.exp( torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment) scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1) signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0) signal = F.pad(signal, [0, 0, 0, channels % 2]) signal = signal.view(1, channels, length) return signal
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4): b, channels, length = x.size() signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) return x + signal.to(dtype=x.dtype, device=x.device)
def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1): b, channels, length = x.size() signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
def subsequent_mask(length): mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0) return mask
@torch.jit.scriptdef fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): n_channels_int = n_channels[0] in_act = input_a + input_b t_act = torch.tanh(in_act[:, :n_channels_int, :]) s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) acts = t_act * s_act return acts
def convert_pad_shape(pad_shape): l = pad_shape[::-1] pad_shape = [item for sublist in l for item in sublist] return pad_shape
def shift_1d(x): x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1] return x
def sequence_mask(length, max_length=None): if max_length is None: max_length = length.max() x = torch.arange(max_length, dtype=length.dtype, device=length.device) return x.unsqueeze(0) < length.unsqueeze(1)
def generate_path(duration, mask): """ duration: [b, 1, t_x] mask: [b, 1, t_y, t_x] """ device = duration.device b, _, t_y, t_x = mask.shape cum_duration = torch.cumsum(duration, -1) cum_duration_flat = cum_duration.view(b * t_x) path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype) path = path.view(b, t_x, t_y) path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1] path = path.unsqueeze(1).transpose(2,3) * mask return path
def clip_grad_value_(parameters, clip_value, norm_type=2): if isinstance(parameters, torch.Tensor): parameters = [parameters] parameters = list(filter(lambda p: p.grad is not None, parameters)) norm_type = float(norm_type) if clip_value is not None: clip_value = float(clip_value)
total_norm = 0 for p in parameters: param_norm = p.grad.data.norm(norm_type) total_norm += param_norm.item() ** norm_type if clip_value is not None: p.grad.data.clamp_(min=-clip_value, max=clip_value) total_norm = total_norm ** (1. / norm_type) return total_norm123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354{ "train": { "log_interval": 200, "eval_interval": 10000, "seed": 1234, "epochs": 10000, "learning_rate": 2e-4, "betas": [0.8, 0.99], "eps": 1e-9, "batch_size": 64, "fp16_run": false, "lr_decay": 0.999875, "segment_size": 8640, "init_lr_ratio": 1, "warmup_epochs": 0, "c_mel": 45, "c_kl": 1.0, "use_sr": true, "max_speclen": 128, "port": "8008" }, "data": { "training_files":"filelists/train.txt", "validation_files":"filelists/val.txt", "max_wav_value": 32768.0, "sampling_rate": 16000, "filter_length": 1280, "hop_length": 320, "win_length": 1280, "n_mel_channels": 80, "mel_fmin": 0.0, "mel_fmax": null }, "model": { "inter_channels": 192, "hidden_channels": 192, "filter_channels": 768, "n_heads": 2, "n_layers": 6, "kernel_size": 3, "p_dropout": 0.1, "resblock": "1", "resblock_kernel_sizes": [3,7,11], "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]], "upsample_rates": [10,6,4,2], "upsample_initial_channel": 512, "upsample_kernel_sizes": [16,16,4,4], "n_layers_q": 3, "use_spectral_norm": false, "gin_channels": 256, "ssl_dim": 1024, "use_spk": true }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354{ "train": { "log_interval": 200, "eval_interval": 10000, "seed": 1234, "epochs": 10000, "learning_rate": 2e-4, "betas": [0.8, 0.99], "eps": 1e-9, "batch_size": 64, "fp16_run": false, "lr_decay": 0.999875, "segment_size": 8960, "init_lr_ratio": 1, "warmup_epochs": 0, "c_mel": 45, "c_kl": 1.0, "use_sr": true, "max_speclen": 128, "port": "8001" }, "data": { "training_files":"filelists/train.txt", "validation_files":"filelists/val.txt", "max_wav_value": 32768.0, "sampling_rate": 16000, "filter_length": 1280, "hop_length": 320, "win_length": 1280, "n_mel_channels": 80, "mel_fmin": 0.0, "mel_fmax": null }, "model": { "inter_channels": 192, "hidden_channels": 192, "filter_channels": 768, "n_heads": 2, "n_layers": 6, "kernel_size": 3, "p_dropout": 0.1, "resblock": "1", "resblock_kernel_sizes": [3,7,11], "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]], "upsample_rates": [10,8,2,2], "upsample_initial_channel": 512, "upsample_kernel_sizes": [16,16,4,4], "n_layers_q": 3, "use_spectral_norm": false, "gin_channels": 256, "ssl_dim": 1024, "use_spk": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354{ "train": { "log_interval": 200, "eval_interval": 10000, "seed": 1234, "epochs": 10000, "learning_rate": 2e-4, "betas": [0.8, 0.99], "eps": 1e-9, "batch_size": 64, "fp16_run": false, "lr_decay": 0.999875, "segment_size": 8960, "init_lr_ratio": 1, "warmup_epochs": 0, "c_mel": 45, "c_kl": 1.0, "use_sr": true, "max_speclen": 128, "port": "8001" }, "data": { "training_files":"filelists/train.txt", "validation_files":"filelists/val.txt", "max_wav_value": 32768.0, "sampling_rate": 16000, "filter_length": 1280, "hop_length": 320, "win_length": 1280, "n_mel_channels": 80, "mel_fmin": 0.0, "mel_fmax": null }, "model": { "inter_channels": 192, "hidden_channels": 192, "filter_channels": 768, "n_heads": 2, "n_layers": 6, "kernel_size": 3, "p_dropout": 0.1, "resblock": "1", "resblock_kernel_sizes": [3,7,11], "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]], "upsample_rates": [10,8,2,2], "upsample_initial_channel": 512, "upsample_kernel_sizes": [16,16,4,4], "n_layers_q": 3, "use_spectral_norm": false, "gin_channels": 256, "ssl_dim": 1024, "use_spk": true }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import mathimport osimport randomimport torchfrom torch import nnimport torch.nn.functional as Fimport torch.utils.dataimport numpy as npimport librosaimport librosa.util as librosa_utilfrom librosa.util import normalize, pad_center, tinyfrom scipy.signal import get_windowfrom scipy.io.wavfile import readfrom librosa.filters import mel as librosa_mel_fn
MAX_WAV_VALUE = 32768.0
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return torch.log(torch.clamp(x, min=clip_val) * C)
def dynamic_range_decompression_torch(x, C=1): """ PARAMS ------ C: compression factor used to compress """ return torch.exp(x) / C
def spectral_normalize_torch(magnitudes): output = dynamic_range_compression_torch(magnitudes) return output
def spectral_de_normalize_torch(magnitudes): output = dynamic_range_decompression_torch(magnitudes) return output
mel_basis = {}hann_window = {}
def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False): if torch.min(y) < -1.: print('min value is ', torch.min(y)) if torch.max(y) > 1.: print('max value is ', torch.max(y))
global hann_window dtype_device = str(y.dtype) + '_' + str(y.device) wnsize_dtype_device = str(win_size) + '_' + dtype_device if wnsize_dtype_device not in hann_window: hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect') y = y.squeeze(1)
spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device], center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6) return spec
def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax): global mel_basis dtype_device = str(spec.dtype) + '_' + str(spec.device) fmax_dtype_device = str(fmax) + '_' + dtype_device if fmax_dtype_device not in mel_basis: mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax) mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device) spec = torch.matmul(mel_basis[fmax_dtype_device], spec) spec = spectral_normalize_torch(spec) return spec
def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False): if torch.min(y) < -1.: print('min value is ', torch.min(y)) if torch.max(y) > 1.: print('max value is ', torch.max(y))
global mel_basis, hann_window dtype_device = str(y.dtype) + '_' + str(y.device) fmax_dtype_device = str(fmax) + '_' + dtype_device wnsize_dtype_device = str(win_size) + '_' + dtype_device if fmax_dtype_device not in mel_basis: mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax) mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device) if wnsize_dtype_device not in hann_window: hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect') y = y.squeeze(1)
spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device], center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
spec = torch.matmul(mel_basis[fmax_dtype_device], spec) spec = spectral_normalize_torch(spec)
return spec123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351import copyimport mathimport torchfrom torch import nnfrom torch.nn import functional as F
import commonsimport modules
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2dfrom torch.nn.utils import weight_norm, remove_weight_norm, spectral_normfrom commons import init_weights, get_padding
class ResidualCouplingBlock(nn.Module): def __init__(self, channels, hidden_channels, kernel_size, dilation_rate, n_layers, n_flows=4, gin_channels=0): super().__init__() self.channels = channels self.hidden_channels = hidden_channels self.kernel_size = kernel_size self.dilation_rate = dilation_rate self.n_layers = n_layers self.n_flows = n_flows self.gin_channels = gin_channels
self.flows = nn.ModuleList() for i in range(n_flows): self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True)) self.flows.append(modules.Flip())
def forward(self, x, x_mask, g=None, reverse=False): if not reverse: for flow in self.flows: x, _ = flow(x, x_mask, g=g, reverse=reverse) else: for flow in reversed(self.flows): x = flow(x, x_mask, g=g, reverse=reverse) return x
class Encoder(nn.Module): def __init__(self, in_channels, out_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.hidden_channels = hidden_channels self.kernel_size = kernel_size self.dilation_rate = dilation_rate self.n_layers = n_layers self.gin_channels = gin_channels
self.pre = nn.Conv1d(in_channels, hidden_channels, 1) self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels) self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
def forward(self, x, x_lengths, g=None): x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) x = self.pre(x) * x_mask x = self.enc(x, x_mask, g=g) stats = self.proj(x) * x_mask m, logs = torch.split(stats, self.out_channels, dim=1) z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask return z, m, logs, x_mask
class Generator(torch.nn.Module): def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0): super(Generator, self).__init__() self.num_kernels = len(resblock_kernel_sizes) self.num_upsamples = len(upsample_rates) self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3) resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
self.ups = nn.ModuleList() for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): self.ups.append(weight_norm( ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)), k, u, padding=(k-u)//2)))
self.resblocks = nn.ModuleList() for i in range(len(self.ups)): ch = upsample_initial_channel//(2**(i+1)) for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)): self.resblocks.append(resblock(ch, k, d))
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) self.ups.apply(init_weights)
if gin_channels != 0: self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
def forward(self, x, g=None): x = self.conv_pre(x) if g is not None: x = x + self.cond(g)
for i in range(self.num_upsamples): x = F.leaky_relu(x, modules.LRELU_SLOPE) x = self.ups[i](x) xs = None for j in range(self.num_kernels): if xs is None: xs = self.resblocks[i*self.num_kernels+j](x) else: xs += self.resblocks[i*self.num_kernels+j](x) x = xs / self.num_kernels x = F.leaky_relu(x) x = self.conv_post(x) x = torch.tanh(x)
return x
def remove_weight_norm(self): print('Removing weight norm...') for l in self.ups: remove_weight_norm(l) for l in self.resblocks: l.remove_weight_norm()
class DiscriminatorP(torch.nn.Module): def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): super(DiscriminatorP, self).__init__() self.period = period self.use_spectral_norm = use_spectral_norm norm_f = weight_norm if use_spectral_norm == False else spectral_norm self.convs = nn.ModuleList([ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))), ]) self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
def forward(self, x): fmap = []
# 1d to 2d b, c, t = x.shape if t % self.period != 0: # pad first n_pad = self.period - (t % self.period) x = F.pad(x, (0, n_pad), "reflect") t = t + n_pad x = x.view(b, c, t // self.period, self.period)
for l in self.convs: x = l(x) x = F.leaky_relu(x, modules.LRELU_SLOPE) fmap.append(x) x = self.conv_post(x) fmap.append(x) x = torch.flatten(x, 1, -1)
return x, fmap
class DiscriminatorS(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(DiscriminatorS, self).__init__() norm_f = weight_norm if use_spectral_norm == False else spectral_norm self.convs = nn.ModuleList([ norm_f(Conv1d(1, 16, 15, 1, padding=7)), norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), ]) self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
def forward(self, x): fmap = []
for l in self.convs: x = l(x) x = F.leaky_relu(x, modules.LRELU_SLOPE) fmap.append(x) x = self.conv_post(x) fmap.append(x) x = torch.flatten(x, 1, -1)
return x, fmap
class MultiPeriodDiscriminator(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(MultiPeriodDiscriminator, self).__init__() periods = [2,3,5,7,11]
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods] self.discriminators = nn.ModuleList(discs)
def forward(self, y, y_hat): y_d_rs = [] y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) y_d_rs.append(y_d_r) y_d_gs.append(y_d_g) fmap_rs.append(fmap_r) fmap_gs.append(fmap_g)
return y_d_rs, y_d_gs, fmap_rs, fmap_gs class SpeakerEncoder(torch.nn.Module): def __init__(self, mel_n_channels=80, model_num_layers=3, model_hidden_size=256, model_embedding_size=256): super(SpeakerEncoder, self).__init__() self.lstm = nn.LSTM(mel_n_channels, model_hidden_size, model_num_layers, batch_first=True) self.linear = nn.Linear(model_hidden_size, model_embedding_size) self.relu = nn.ReLU()
def forward(self, mels): self.lstm.flatten_parameters() _, (hidden, _) = self.lstm(mels) embeds_raw = self.relu(self.linear(hidden[-1])) return embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True) def compute_partial_slices(self, total_frames, partial_frames, partial_hop): mel_slices = [] for i in range(0, total_frames-partial_frames, partial_hop): mel_range = torch.arange(i, i+partial_frames) mel_slices.append(mel_range) return mel_slices def embed_utterance(self, mel, partial_frames=128, partial_hop=64): mel_len = mel.size(1) last_mel = mel[:,-partial_frames:] if mel_len > partial_frames: mel_slices = self.compute_partial_slices(mel_len, partial_frames, partial_hop) mels = list(mel[:,s] for s in mel_slices) mels.append(last_mel) mels = torch.stack(tuple(mels), 0).squeeze(1) with torch.no_grad(): partial_embeds = self(mels) embed = torch.mean(partial_embeds, axis=0).unsqueeze(0) #embed = embed / torch.linalg.norm(embed, 2) else: with torch.no_grad(): embed = self(last_mel) return embed
class SynthesizerTrn(nn.Module): """ Synthesizer for Training """
def __init__(self, spec_channels, segment_size, inter_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels, ssl_dim, use_spk, **kwargs):
super().__init__() self.spec_channels = spec_channels self.inter_channels = inter_channels self.hidden_channels = hidden_channels self.filter_channels = filter_channels self.n_heads = n_heads self.n_layers = n_layers self.kernel_size = kernel_size self.p_dropout = p_dropout self.resblock = resblock self.resblock_kernel_sizes = resblock_kernel_sizes self.resblock_dilation_sizes = resblock_dilation_sizes self.upsample_rates = upsample_rates self.upsample_initial_channel = upsample_initial_channel self.upsample_kernel_sizes = upsample_kernel_sizes self.segment_size = segment_size self.gin_channels = gin_channels self.ssl_dim = ssl_dim self.use_spk = use_spk
self.enc_p = Encoder(ssl_dim, inter_channels, hidden_channels, 5, 1, 16) self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels) self.enc_q = Encoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels) self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels) if not self.use_spk: self.enc_spk = SpeakerEncoder(model_hidden_size=gin_channels, model_embedding_size=gin_channels)
def forward(self, c, spec, g=None, mel=None, c_lengths=None, spec_lengths=None): if c_lengths == None: c_lengths = (torch.ones(c.size(0)) * c.size(-1)).to(c.device) if spec_lengths == None: spec_lengths = (torch.ones(spec.size(0)) * spec.size(-1)).to(spec.device) if not self.use_spk: g = self.enc_spk(mel.transpose(1,2)) g = g.unsqueeze(-1) _, m_p, logs_p, _ = self.enc_p(c, c_lengths) z, m_q, logs_q, spec_mask = self.enc_q(spec, spec_lengths, g=g) z_p = self.flow(z, spec_mask, g=g)
z_slice, ids_slice = commons.rand_slice_segments(z, spec_lengths, self.segment_size) o = self.dec(z_slice, g=g) return o, ids_slice, spec_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
def infer(self, c, g=None, mel=None, c_lengths=None): if c_lengths == None: c_lengths = (torch.ones(c.size(0)) * c.size(-1)).to(c.device) if not self.use_spk: g = self.enc_spk.embed_utterance(mel.transpose(1,2)) g = g.unsqueeze(-1)
z_p, m_p, logs_p, c_mask = self.enc_p(c, c_lengths) z = self.flow(z_p, c_mask, g=g, reverse=True) o = self.dec(z * c_mask, g=g) return o123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342import copyimport mathimport numpy as npimport scipyimport torchfrom torch import nnfrom torch.nn import functional as F
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2dfrom torch.nn.utils import weight_norm, remove_weight_norm
import commonsfrom commons import init_weights, get_padding
LRELU_SLOPE = 0.1
class LayerNorm(nn.Module): def __init__(self, channels, eps=1e-5): super().__init__() self.channels = channels self.eps = eps
self.gamma = nn.Parameter(torch.ones(channels)) self.beta = nn.Parameter(torch.zeros(channels))
def forward(self, x): x = x.transpose(1, -1) x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps) return x.transpose(1, -1)
class ConvReluNorm(nn.Module): def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout): super().__init__() self.in_channels = in_channels self.hidden_channels = hidden_channels self.out_channels = out_channels self.kernel_size = kernel_size self.n_layers = n_layers self.p_dropout = p_dropout assert n_layers > 1, "Number of layers should be larger than 0."
self.conv_layers = nn.ModuleList() self.norm_layers = nn.ModuleList() self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2)) self.norm_layers.append(LayerNorm(hidden_channels)) self.relu_drop = nn.Sequential( nn.ReLU(), nn.Dropout(p_dropout)) for _ in range(n_layers-1): self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2)) self.norm_layers.append(LayerNorm(hidden_channels)) self.proj = nn.Conv1d(hidden_channels, out_channels, 1) self.proj.weight.data.zero_() self.proj.bias.data.zero_()
def forward(self, x, x_mask): x_org = x for i in range(self.n_layers): x = self.conv_layers[i](x * x_mask) x = self.norm_layers[i](x) x = self.relu_drop(x) x = x_org + self.proj(x) return x * x_mask
class DDSConv(nn.Module): """ Dialted and Depth-Separable Convolution """ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.): super().__init__() self.channels = channels self.kernel_size = kernel_size self.n_layers = n_layers self.p_dropout = p_dropout
self.drop = nn.Dropout(p_dropout) self.convs_sep = nn.ModuleList() self.convs_1x1 = nn.ModuleList() self.norms_1 = nn.ModuleList() self.norms_2 = nn.ModuleList() for i in range(n_layers): dilation = kernel_size ** i padding = (kernel_size * dilation - dilation) // 2 self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size, groups=channels, dilation=dilation, padding=padding )) self.convs_1x1.append(nn.Conv1d(channels, channels, 1)) self.norms_1.append(LayerNorm(channels)) self.norms_2.append(LayerNorm(channels))
def forward(self, x, x_mask, g=None): if g is not None: x = x + g for i in range(self.n_layers): y = self.convs_sep[i](x * x_mask) y = self.norms_1[i](y) y = F.gelu(y) y = self.convs_1x1[i](y) y = self.norms_2[i](y) y = F.gelu(y) y = self.drop(y) x = x + y return x * x_mask
class WN(torch.nn.Module): def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0): super(WN, self).__init__() assert(kernel_size % 2 == 1) self.hidden_channels =hidden_channels self.kernel_size = kernel_size, self.dilation_rate = dilation_rate self.n_layers = n_layers self.gin_channels = gin_channels self.p_dropout = p_dropout
self.in_layers = torch.nn.ModuleList() self.res_skip_layers = torch.nn.ModuleList() self.drop = nn.Dropout(p_dropout)
if gin_channels != 0: cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1) self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
for i in range(n_layers): dilation = dilation_rate ** i padding = int((kernel_size * dilation - dilation) / 2) in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size, dilation=dilation, padding=padding) in_layer = torch.nn.utils.weight_norm(in_layer, name='weight') self.in_layers.append(in_layer)
# last one is not necessary if i < n_layers - 1: res_skip_channels = 2 * hidden_channels else: res_skip_channels = hidden_channels
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1) res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight') self.res_skip_layers.append(res_skip_layer)
def forward(self, x, x_mask, g=None, **kwargs): output = torch.zeros_like(x) n_channels_tensor = torch.IntTensor([self.hidden_channels])
if g is not None: g = self.cond_layer(g)
for i in range(self.n_layers): x_in = self.in_layers[i](x) if g is not None: cond_offset = i * 2 * self.hidden_channels g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:] else: g_l = torch.zeros_like(x_in)
acts = commons.fused_add_tanh_sigmoid_multiply( x_in, g_l, n_channels_tensor) acts = self.drop(acts)
res_skip_acts = self.res_skip_layers[i](acts) if i < self.n_layers - 1: res_acts = res_skip_acts[:,:self.hidden_channels,:] x = (x + res_acts) * x_mask output = output + res_skip_acts[:,self.hidden_channels:,:] else: output = output + res_skip_acts return output * x_mask
def remove_weight_norm(self): if self.gin_channels != 0: torch.nn.utils.remove_weight_norm(self.cond_layer) for l in self.in_layers: torch.nn.utils.remove_weight_norm(l) for l in self.res_skip_layers: torch.nn.utils.remove_weight_norm(l)
class ResBlock1(torch.nn.Module): def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)): super(ResBlock1, self).__init__() self.convs1 = nn.ModuleList([ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], padding=get_padding(kernel_size, dilation[0]))), weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1], padding=get_padding(kernel_size, dilation[1]))), weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2], padding=get_padding(kernel_size, dilation[2]))) ]) self.convs1.apply(init_weights)
self.convs2 = nn.ModuleList([ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, padding=get_padding(kernel_size, 1))), weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, padding=get_padding(kernel_size, 1))), weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, padding=get_padding(kernel_size, 1))) ]) self.convs2.apply(init_weights)
def forward(self, x, x_mask=None): for c1, c2 in zip(self.convs1, self.convs2): xt = F.leaky_relu(x, LRELU_SLOPE) if x_mask is not None: xt = xt * x_mask xt = c1(xt) xt = F.leaky_relu(xt, LRELU_SLOPE) if x_mask is not None: xt = xt * x_mask xt = c2(xt) x = xt + x if x_mask is not None: x = x * x_mask return x
def remove_weight_norm(self): for l in self.convs1: remove_weight_norm(l) for l in self.convs2: remove_weight_norm(l)
class ResBlock2(torch.nn.Module): def __init__(self, channels, kernel_size=3, dilation=(1, 3)): super(ResBlock2, self).__init__() self.convs = nn.ModuleList([ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], padding=get_padding(kernel_size, dilation[0]))), weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1], padding=get_padding(kernel_size, dilation[1]))) ]) self.convs.apply(init_weights)
def forward(self, x, x_mask=None): for c in self.convs: xt = F.leaky_relu(x, LRELU_SLOPE) if x_mask is not None: xt = xt * x_mask xt = c(xt) x = xt + x if x_mask is not None: x = x * x_mask return x
def remove_weight_norm(self): for l in self.convs: remove_weight_norm(l)
class Log(nn.Module): def forward(self, x, x_mask, reverse=False, **kwargs): if not reverse: y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask logdet = torch.sum(-y, [1, 2]) return y, logdet else: x = torch.exp(x) * x_mask return x
class Flip(nn.Module): def forward(self, x, *args, reverse=False, **kwargs): x = torch.flip(x, [1]) if not reverse: logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device) return x, logdet else: return x
class ElementwiseAffine(nn.Module): def __init__(self, channels): super().__init__() self.channels = channels self.m = nn.Parameter(torch.zeros(channels,1)) self.logs = nn.Parameter(torch.zeros(channels,1))
def forward(self, x, x_mask, reverse=False, **kwargs): if not reverse: y = self.m + torch.exp(self.logs) * x y = y * x_mask logdet = torch.sum(self.logs * x_mask, [1,2]) return y, logdet else: x = (x - self.m) * torch.exp(-self.logs) * x_mask return x
class ResidualCouplingLayer(nn.Module): def __init__(self, channels, hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=0, gin_channels=0, mean_only=False): assert channels % 2 == 0, "channels should be divisible by 2" super().__init__() self.channels = channels self.hidden_channels = hidden_channels self.kernel_size = kernel_size self.dilation_rate = dilation_rate self.n_layers = n_layers self.half_channels = channels // 2 self.mean_only = mean_only
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1) self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels) self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1) self.post.weight.data.zero_() self.post.bias.data.zero_()
def forward(self, x, x_mask, g=None, reverse=False): x0, x1 = torch.split(x, [self.half_channels]*2, 1) h = self.pre(x0) * x_mask h = self.enc(h, x_mask, g=g) stats = self.post(h) * x_mask if not self.mean_only: m, logs = torch.split(stats, [self.half_channels]*2, 1) else: m = stats logs = torch.zeros_like(m)
if not reverse: x1 = m + x1 * torch.exp(logs) * x_mask x = torch.cat([x0, x1], 1) logdet = torch.sum(logs, [1,2]) return x, logdet else: x1 = (x1 - m) * torch.exp(-logs) * x_mask x = torch.cat([x0, x1], 1) return x1234567numpyscipytorchtransformerslibrosa==0.8.1webrtcvad==2.0.10gradio==3.22.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107from scipy.ndimage.morphology import binary_dilationfrom speaker_encoder.params_data import *from pathlib import Pathfrom typing import Optional, Unionimport numpy as npimport webrtcvadimport librosaimport struct
int16_max = (2 ** 15) - 1
def preprocess_wav(fpath_or_wav: Union[str, Path, np.ndarray], source_sr: Optional[int] = None): """ Applies the preprocessing operations used in training the Speaker Encoder to a waveform either on disk or in memory. The waveform will be resampled to match the data hyperparameters.
:param fpath_or_wav: either a filepath to an audio file (many extensions are supported, not just .wav), either the waveform as a numpy array of floats. :param source_sr: if passing an audio waveform, the sampling rate of the waveform before preprocessing. After preprocessing, the waveform's sampling rate will match the data hyperparameters. If passing a filepath, the sampling rate will be automatically detected and this argument will be ignored. """ # Load the wav from disk if needed if isinstance(fpath_or_wav, str) or isinstance(fpath_or_wav, Path): wav, source_sr = librosa.load(fpath_or_wav, sr=None) else: wav = fpath_or_wav # Resample the wav if needed if source_sr is not None and source_sr != sampling_rate: wav = librosa.resample(wav, source_sr, sampling_rate) # Apply the preprocessing: normalize volume and shorten long silences wav = normalize_volume(wav, audio_norm_target_dBFS, increase_only=True) wav = trim_long_silences(wav) return wav
def wav_to_mel_spectrogram(wav): """ Derives a mel spectrogram ready to be used by the encoder from a preprocessed audio waveform. Note: this not a log-mel spectrogram. """ frames = librosa.feature.melspectrogram( y=wav, sr=sampling_rate, n_fft=int(sampling_rate * mel_window_length / 1000), hop_length=int(sampling_rate * mel_window_step / 1000), n_mels=mel_n_channels ) return frames.astype(np.float32).T
def trim_long_silences(wav): """ Ensures that segments without voice in the waveform remain no longer than a threshold determined by the VAD parameters in params.py.
:param wav: the raw waveform as a numpy array of floats :return: the same waveform with silences trimmed away (length <= original wav length) """ # Compute the voice detection window size samples_per_window = (vad_window_length * sampling_rate) // 1000 # Trim the end of the audio to have a multiple of the window size wav = wav[:len(wav) - (len(wav) % samples_per_window)] # Convert the float waveform to 16-bit mono PCM pcm_wave = struct.pack("%dh" % len(wav), *(np.round(wav * int16_max)).astype(np.int16)) # Perform voice activation detection voice_flags = [] vad = webrtcvad.Vad(mode=3) for window_start in range(0, len(wav), samples_per_window): window_end = window_start + samples_per_window voice_flags.append(vad.is_speech(pcm_wave[window_start * 2:window_end * 2], sample_rate=sampling_rate)) voice_flags = np.array(voice_flags) # Smooth the voice detection with a moving average def moving_average(array, width): array_padded = np.concatenate((np.zeros((width - 1) // 2), array, np.zeros(width // 2))) ret = np.cumsum(array_padded, dtype=float) ret[width:] = ret[width:] - ret[:-width] return ret[width - 1:] / width audio_mask = moving_average(voice_flags, vad_moving_average_width) audio_mask = np.round(audio_mask).astype(np.bool) # Dilate the voiced regions audio_mask = binary_dilation(audio_mask, np.ones(vad_max_silence_length + 1)) audio_mask = np.repeat(audio_mask, samples_per_window) return wav[audio_mask == True]
def normalize_volume(wav, target_dBFS, increase_only=False, decrease_only=False): if increase_only and decrease_only: raise ValueError("Both increase only and decrease only are set") dBFS_change = target_dBFS - 10 * np.log10(np.mean(wav ** 2)) if (dBFS_change < 0 and increase_only) or (dBFS_change > 0 and decrease_only): return wav return wav * (10 ** (dBFS_change / 20))123version https://git-lfs.github.com/spec/v1oid sha256:bc7ff82ef75becd495aab2ede3a8220da393a717f178ae9534df355a6173bbcasize 1709037912345678910111213141516171819202122232425262728293031323334353637383940from speaker_encoder import inference as encoderfrom multiprocessing.pool import Poolfrom functools import partialfrom pathlib import Path# from utils import logmmse# from tqdm import tqdm# import numpy as np# import librosa
def embed_utterance(fpaths, encoder_model_fpath): if not encoder.is_loaded(): encoder.load_model(encoder_model_fpath)
# Compute the speaker embedding of the utterance wav_fpath, embed_fpath = fpaths wav = np.load(wav_fpath) wav = encoder.preprocess_wav(wav) embed = encoder.embed_utterance(wav) np.save(embed_fpath, embed, allow_pickle=False) def create_embeddings(outdir_root: Path, wav_dir: Path, encoder_model_fpath: Path, n_processes: int):
wav_dir = outdir_root.joinpath("audio") metadata_fpath = synthesizer_root.joinpath("train.txt") assert wav_dir.exists() and metadata_fpath.exists() embed_dir = synthesizer_root.joinpath("embeds") embed_dir.mkdir(exist_ok=True) # Gather the input wave filepath and the target output embed filepath with metadata_fpath.open("r") as metadata_file: metadata = [line.split("|") for line in metadata_file] fpaths = [(wav_dir.joinpath(m[0]), embed_dir.joinpath(m[2])) for m in metadata] # TODO: improve on the multiprocessing, it's terrible. Disk I/O is the bottleneck here. # Embed the utterances in separate threads func = partial(embed_utterance, encoder_model_fpath=encoder_model_fpath) job = Pool(n_processes).imap(func, fpaths) list(tqdm(job, "Embedding", len(fpaths), unit="utterances"))123456789101112131415161718192021222324252627282930313233343536373839404142434445librispeech_datasets = { "train": { "clean": ["LibriSpeech/train-clean-100", "LibriSpeech/train-clean-360"], "other": ["LibriSpeech/train-other-500"] }, "test": { "clean": ["LibriSpeech/test-clean"], "other": ["LibriSpeech/test-other"] }, "dev": { "clean": ["LibriSpeech/dev-clean"], "other": ["LibriSpeech/dev-other"] },}libritts_datasets = { "train": { "clean": ["LibriTTS/train-clean-100", "LibriTTS/train-clean-360"], "other": ["LibriTTS/train-other-500"] }, "test": { "clean": ["LibriTTS/test-clean"], "other": ["LibriTTS/test-other"] }, "dev": { "clean": ["LibriTTS/dev-clean"], "other": ["LibriTTS/dev-other"] },}voxceleb_datasets = { "voxceleb1" : { "train": ["VoxCeleb1/wav"], "test": ["VoxCeleb1/test_wav"] }, "voxceleb2" : { "train": ["VoxCeleb2/dev/aac"], "test": ["VoxCeleb2/test_wav"] }}
other_datasets = [ "LJSpeech-1.1", "VCTK-Corpus/wav48",]
anglophone_nationalites = ["australia", "canada", "ireland", "uk", "usa"]12from speaker_encoder.data_objects.speaker_verification_dataset import SpeakerVerificationDatasetfrom speaker_encoder.data_objects.speaker_verification_dataset import SpeakerVerificationDataLoader12345678910111213141516171819202122232425262728293031323334353637import random
class RandomCycler: """ Creates an internal copy of a sequence and allows access to its items in a constrained random order. For a source sequence of n items and one or several consecutive queries of a total of m items, the following guarantees hold (one implies the other): - Each item will be returned between m // n and ((m - 1) // n) + 1 times. - Between two appearances of the same item, there may be at most 2 * (n - 1) other items. """ def __init__(self, source): if len(source) == 0: raise Exception("Can't create RandomCycler from an empty collection") self.all_items = list(source) self.next_items = [] def sample(self, count: int): shuffle = lambda l: random.sample(l, len(l)) out = [] while count > 0: if count >= len(self.all_items): out.extend(shuffle(list(self.all_items))) count -= len(self.all_items) continue n = min(count, len(self.next_items)) out.extend(self.next_items[:n]) count -= n self.next_items = self.next_items[n:] if len(self.next_items) == 0: self.next_items = shuffle(list(self.all_items)) return out def __next__(self): return self.sample(1)[0]
12345678910111213141516171819202122232425262728293031323334353637383940from speaker_encoder.data_objects.random_cycler import RandomCyclerfrom speaker_encoder.data_objects.utterance import Utterancefrom pathlib import Path
# Contains the set of utterances of a single speakerclass Speaker: def __init__(self, root: Path): self.root = root self.name = root.name self.utterances = None self.utterance_cycler = None def _load_utterances(self): with self.root.joinpath("_sources.txt").open("r") as sources_file: sources = [l.split(",") for l in sources_file] sources = {frames_fname: wave_fpath for frames_fname, wave_fpath in sources} self.utterances = [Utterance(self.root.joinpath(f), w) for f, w in sources.items()] self.utterance_cycler = RandomCycler(self.utterances) def random_partial(self, count, n_frames): """ Samples a batch of <count> unique partial utterances from the disk in a way that all utterances come up at least once every two cycles and in a random order every time. :param count: The number of partial utterances to sample from the set of utterances from that speaker. Utterances are guaranteed not to be repeated if <count> is not larger than the number of utterances available. :param n_frames: The number of frames in the partial utterance. :return: A list of tuples (utterance, frames, range) where utterance is an Utterance, frames are the frames of the partial utterances and range is the range of the partial utterance with regard to the complete utterance. """ if self.utterances is None: self._load_utterances()
utterances = self.utterance_cycler.sample(count)
a = [(u,) + u.random_partial(n_frames) for u in utterances]
return a123456789101112import numpy as npfrom typing import Listfrom speaker_encoder.data_objects.speaker import Speaker
class SpeakerBatch: def __init__(self, speakers: List[Speaker], utterances_per_speaker: int, n_frames: int): self.speakers = speakers self.partials = {s: s.random_partial(utterances_per_speaker, n_frames) for s in speakers} # Array of shape (n_speakers * n_utterances, n_frames, mel_n), e.g. for 3 speakers with # 4 utterances each of 160 frames of 40 mel coefficients: (12, 160, 40) self.data = np.array([frames for s in speakers for _, frames, _ in self.partials[s]])1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556from speaker_encoder.data_objects.random_cycler import RandomCyclerfrom speaker_encoder.data_objects.speaker_batch import SpeakerBatchfrom speaker_encoder.data_objects.speaker import Speakerfrom speaker_encoder.params_data import partials_n_framesfrom torch.utils.data import Dataset, DataLoaderfrom pathlib import Path
# TODO: improve with a pool of speakers for data efficiency
class SpeakerVerificationDataset(Dataset): def __init__(self, datasets_root: Path): self.root = datasets_root speaker_dirs = [f for f in self.root.glob("*") if f.is_dir()] if len(speaker_dirs) == 0: raise Exception("No speakers found. Make sure you are pointing to the directory " "containing all preprocessed speaker directories.") self.speakers = [Speaker(speaker_dir) for speaker_dir in speaker_dirs] self.speaker_cycler = RandomCycler(self.speakers)
def __len__(self): return int(1e10) def __getitem__(self, index): return next(self.speaker_cycler) def get_logs(self): log_string = "" for log_fpath in self.root.glob("*.txt"): with log_fpath.open("r") as log_file: log_string += "".join(log_file.readlines()) return log_string class SpeakerVerificationDataLoader(DataLoader): def __init__(self, dataset, speakers_per_batch, utterances_per_speaker, sampler=None, batch_sampler=None, num_workers=0, pin_memory=False, timeout=0, worker_init_fn=None): self.utterances_per_speaker = utterances_per_speaker
super().__init__( dataset=dataset, batch_size=speakers_per_batch, shuffle=False, sampler=sampler, batch_sampler=batch_sampler, num_workers=num_workers, collate_fn=self.collate, pin_memory=pin_memory, drop_last=False, timeout=timeout, worker_init_fn=worker_init_fn )
def collate(self, speakers): return SpeakerBatch(speakers, self.utterances_per_speaker, partials_n_frames) 1234567891011121314151617181920212223242526import numpy as np
class Utterance: def __init__(self, frames_fpath, wave_fpath): self.frames_fpath = frames_fpath self.wave_fpath = wave_fpath def get_frames(self): return np.load(self.frames_fpath)
def random_partial(self, n_frames): """ Crops the frames into a partial utterance of n_frames :param n_frames: The number of frames of the partial utterance :return: the partial utterance frames and a tuple indicating the start and end of the partial utterance in the complete utterance. """ frames = self.get_frames() if frames.shape[0] == n_frames: start = 0 else: start = np.random.randint(0, frames.shape[0] - n_frames) end = start + n_frames return frames[start:end], (start, end)12345678910111213141516171819202122232425262728293031## Mel-filterbankmel_window_length = 25 # In millisecondsmel_window_step = 10 # In millisecondsmel_n_channels = 40
## Audiosampling_rate = 16000# Number of spectrogram frames in a partial utterancepartials_n_frames = 160 # 1600 ms
## Voice Activation Detection# Window size of the VAD. Must be either 10, 20 or 30 milliseconds.# This sets the granularity of the VAD. Should not need to be changed.vad_window_length = 30 # In milliseconds# Number of frames to average together when performing the moving average smoothing.# The larger this value, the larger the VAD variations must be to not get smoothed out. vad_moving_average_width = 8# Maximum number of consecutive silent frames a segment can have.vad_max_silence_length = 6
## Audio volume normalizationaudio_norm_target_dBFS = -30
## Model parametersmodel_hidden_size = 256model_embedding_size = 256model_num_layers = 3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177from speaker_encoder.params_data import *from speaker_encoder.model import SpeakerEncoderfrom speaker_encoder.audio import preprocess_wav # We want to expose this function from herefrom matplotlib import cmfrom speaker_encoder import audiofrom pathlib import Pathimport matplotlib.pyplot as pltimport numpy as npimport torch
_model = None # type: SpeakerEncoder_device = None # type: torch.device
def load_model(weights_fpath: Path, device=None): """ Loads the model in memory. If this function is not explicitely called, it will be run on the first call to embed_frames() with the default weights file. :param weights_fpath: the path to saved model weights. :param device: either a torch device or the name of a torch device (e.g. "cpu", "cuda"). The model will be loaded and will run on this device. Outputs will however always be on the cpu. If None, will default to your GPU if it"s available, otherwise your CPU. """ # TODO: I think the slow loading of the encoder might have something to do with the device it # was saved on. Worth investigating. global _model, _device if device is None: _device = torch.device("cuda" if torch.cuda.is_available() else "cpu") elif isinstance(device, str): _device = torch.device(device) _model = SpeakerEncoder(_device, torch.device("cpu")) checkpoint = torch.load(weights_fpath) _model.load_state_dict(checkpoint["model_state"]) _model.eval() print("Loaded encoder \"%s\" trained to step %d" % (weights_fpath.name, checkpoint["step"])) def is_loaded(): return _model is not None
def embed_frames_batch(frames_batch): """ Computes embeddings for a batch of mel spectrogram. :param frames_batch: a batch mel of spectrogram as a numpy array of float32 of shape (batch_size, n_frames, n_channels) :return: the embeddings as a numpy array of float32 of shape (batch_size, model_embedding_size) """ if _model is None: raise Exception("Model was not loaded. Call load_model() before inference.") frames = torch.from_numpy(frames_batch).to(_device) embed = _model.forward(frames).detach().cpu().numpy() return embed
def compute_partial_slices(n_samples, partial_utterance_n_frames=partials_n_frames, min_pad_coverage=0.75, overlap=0.5): """ Computes where to split an utterance waveform and its corresponding mel spectrogram to obtain partial utterances of <partial_utterance_n_frames> each. Both the waveform and the mel spectrogram slices are returned, so as to make each partial utterance waveform correspond to its spectrogram. This function assumes that the mel spectrogram parameters used are those defined in params_data.py. The returned ranges may be indexing further than the length of the waveform. It is recommended that you pad the waveform with zeros up to wave_slices[-1].stop. :param n_samples: the number of samples in the waveform :param partial_utterance_n_frames: the number of mel spectrogram frames in each partial utterance :param min_pad_coverage: when reaching the last partial utterance, it may or may not have enough frames. If at least <min_pad_coverage> of <partial_utterance_n_frames> are present, then the last partial utterance will be considered, as if we padded the audio. Otherwise, it will be discarded, as if we trimmed the audio. If there aren't enough frames for 1 partial utterance, this parameter is ignored so that the function always returns at least 1 slice. :param overlap: by how much the partial utterance should overlap. If set to 0, the partial utterances are entirely disjoint. :return: the waveform slices and mel spectrogram slices as lists of array slices. Index respectively the waveform and the mel spectrogram with these slices to obtain the partial utterances. """ assert 0 <= overlap < 1 assert 0 < min_pad_coverage <= 1 samples_per_frame = int((sampling_rate * mel_window_step / 1000)) n_frames = int(np.ceil((n_samples + 1) / samples_per_frame)) frame_step = max(int(np.round(partial_utterance_n_frames * (1 - overlap))), 1)
# Compute the slices wav_slices, mel_slices = [], [] steps = max(1, n_frames - partial_utterance_n_frames + frame_step + 1) for i in range(0, steps, frame_step): mel_range = np.array([i, i + partial_utterance_n_frames]) wav_range = mel_range * samples_per_frame mel_slices.append(slice(*mel_range)) wav_slices.append(slice(*wav_range)) # Evaluate whether extra padding is warranted or not last_wav_range = wav_slices[-1] coverage = (n_samples - last_wav_range.start) / (last_wav_range.stop - last_wav_range.start) if coverage < min_pad_coverage and len(mel_slices) > 1: mel_slices = mel_slices[:-1] wav_slices = wav_slices[:-1] return wav_slices, mel_slices
def embed_utterance(wav, using_partials=True, return_partials=False, **kwargs): """ Computes an embedding for a single utterance. # TODO: handle multiple wavs to benefit from batching on GPU :param wav: a preprocessed (see audio.py) utterance waveform as a numpy array of float32 :param using_partials: if True, then the utterance is split in partial utterances of <partial_utterance_n_frames> frames and the utterance embedding is computed from their normalized average. If False, the utterance is instead computed from feeding the entire spectogram to the network. :param return_partials: if True, the partial embeddings will also be returned along with the wav slices that correspond to the partial embeddings. :param kwargs: additional arguments to compute_partial_splits() :return: the embedding as a numpy array of float32 of shape (model_embedding_size,). If <return_partials> is True, the partial utterances as a numpy array of float32 of shape (n_partials, model_embedding_size) and the wav partials as a list of slices will also be returned. If <using_partials> is simultaneously set to False, both these values will be None instead. """ # Process the entire utterance if not using partials if not using_partials: frames = audio.wav_to_mel_spectrogram(wav) embed = embed_frames_batch(frames[None, ...])[0] if return_partials: return embed, None, None return embed # Compute where to split the utterance into partials and pad if necessary wave_slices, mel_slices = compute_partial_slices(len(wav), **kwargs) max_wave_length = wave_slices[-1].stop if max_wave_length >= len(wav): wav = np.pad(wav, (0, max_wave_length - len(wav)), "constant") # Split the utterance into partials frames = audio.wav_to_mel_spectrogram(wav) frames_batch = np.array([frames[s] for s in mel_slices]) partial_embeds = embed_frames_batch(frames_batch) # Compute the utterance embedding from the partial embeddings raw_embed = np.mean(partial_embeds, axis=0) embed = raw_embed / np.linalg.norm(raw_embed, 2) if return_partials: return embed, partial_embeds, wave_slices return embed
def embed_speaker(wavs, **kwargs): raise NotImplemented()
def plot_embedding_as_heatmap(embed, ax=None, title="", shape=None, color_range=(0, 0.30)): if ax is None: ax = plt.gca() if shape is None: height = int(np.sqrt(len(embed))) shape = (height, -1) embed = embed.reshape(shape) cmap = cm.get_cmap() mappable = ax.imshow(embed, cmap=cmap) cbar = plt.colorbar(mappable, ax=ax, fraction=0.046, pad=0.04) cbar.set_clim(*color_range) ax.set_xticks([]), ax.set_yticks([]) ax.set_title(title)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135from speaker_encoder.params_model import *from speaker_encoder.params_data import *from scipy.interpolate import interp1dfrom sklearn.metrics import roc_curvefrom torch.nn.utils import clip_grad_norm_from scipy.optimize import brentqfrom torch import nnimport numpy as npimport torch
class SpeakerEncoder(nn.Module): def __init__(self, device, loss_device): super().__init__() self.loss_device = loss_device # Network defition self.lstm = nn.LSTM(input_size=mel_n_channels, # 40 hidden_size=model_hidden_size, # 256 num_layers=model_num_layers, # 3 batch_first=True).to(device) self.linear = nn.Linear(in_features=model_hidden_size, out_features=model_embedding_size).to(device) self.relu = torch.nn.ReLU().to(device) # Cosine similarity scaling (with fixed initial parameter values) self.similarity_weight = nn.Parameter(torch.tensor([10.])).to(loss_device) self.similarity_bias = nn.Parameter(torch.tensor([-5.])).to(loss_device)
# Loss self.loss_fn = nn.CrossEntropyLoss().to(loss_device) def do_gradient_ops(self): # Gradient scale self.similarity_weight.grad *= 0.01 self.similarity_bias.grad *= 0.01 # Gradient clipping clip_grad_norm_(self.parameters(), 3, norm_type=2) def forward(self, utterances, hidden_init=None): """ Computes the embeddings of a batch of utterance spectrograms. :param utterances: batch of mel-scale filterbanks of same duration as a tensor of shape (batch_size, n_frames, n_channels) :param hidden_init: initial hidden state of the LSTM as a tensor of shape (num_layers, batch_size, hidden_size). Will default to a tensor of zeros if None. :return: the embeddings as a tensor of shape (batch_size, embedding_size) """ # Pass the input through the LSTM layers and retrieve all outputs, the final hidden state # and the final cell state. out, (hidden, cell) = self.lstm(utterances, hidden_init) # We take only the hidden state of the last layer embeds_raw = self.relu(self.linear(hidden[-1])) # L2-normalize it embeds = embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True) return embeds def similarity_matrix(self, embeds): """ Computes the similarity matrix according the section 2.1 of GE2E.
:param embeds: the embeddings as a tensor of shape (speakers_per_batch, utterances_per_speaker, embedding_size) :return: the similarity matrix as a tensor of shape (speakers_per_batch, utterances_per_speaker, speakers_per_batch) """ speakers_per_batch, utterances_per_speaker = embeds.shape[:2] # Inclusive centroids (1 per speaker). Cloning is needed for reverse differentiation centroids_incl = torch.mean(embeds, dim=1, keepdim=True) centroids_incl = centroids_incl.clone() / torch.norm(centroids_incl, dim=2, keepdim=True)
# Exclusive centroids (1 per utterance) centroids_excl = (torch.sum(embeds, dim=1, keepdim=True) - embeds) centroids_excl /= (utterances_per_speaker - 1) centroids_excl = centroids_excl.clone() / torch.norm(centroids_excl, dim=2, keepdim=True)
# Similarity matrix. The cosine similarity of already 2-normed vectors is simply the dot # product of these vectors (which is just an element-wise multiplication reduced by a sum). # We vectorize the computation for efficiency. sim_matrix = torch.zeros(speakers_per_batch, utterances_per_speaker, speakers_per_batch).to(self.loss_device) mask_matrix = 1 - np.eye(speakers_per_batch, dtype=np.int) for j in range(speakers_per_batch): mask = np.where(mask_matrix[j])[0] sim_matrix[mask, :, j] = (embeds[mask] * centroids_incl[j]).sum(dim=2) sim_matrix[j, :, j] = (embeds[j] * centroids_excl[j]).sum(dim=1) ## Even more vectorized version (slower maybe because of transpose) # sim_matrix2 = torch.zeros(speakers_per_batch, speakers_per_batch, utterances_per_speaker # ).to(self.loss_device) # eye = np.eye(speakers_per_batch, dtype=np.int) # mask = np.where(1 - eye) # sim_matrix2[mask] = (embeds[mask[0]] * centroids_incl[mask[1]]).sum(dim=2) # mask = np.where(eye) # sim_matrix2[mask] = (embeds * centroids_excl).sum(dim=2) # sim_matrix2 = sim_matrix2.transpose(1, 2) sim_matrix = sim_matrix * self.similarity_weight + self.similarity_bias return sim_matrix def loss(self, embeds): """ Computes the softmax loss according the section 2.1 of GE2E. :param embeds: the embeddings as a tensor of shape (speakers_per_batch, utterances_per_speaker, embedding_size) :return: the loss and the EER for this batch of embeddings. """ speakers_per_batch, utterances_per_speaker = embeds.shape[:2] # Loss sim_matrix = self.similarity_matrix(embeds) sim_matrix = sim_matrix.reshape((speakers_per_batch * utterances_per_speaker, speakers_per_batch)) ground_truth = np.repeat(np.arange(speakers_per_batch), utterances_per_speaker) target = torch.from_numpy(ground_truth).long().to(self.loss_device) loss = self.loss_fn(sim_matrix, target) # EER (not backpropagated) with torch.no_grad(): inv_argmax = lambda i: np.eye(1, speakers_per_batch, i, dtype=np.int)[0] labels = np.array([inv_argmax(i) for i in ground_truth]) preds = sim_matrix.detach().cpu().numpy()
# Snippet from https://yangcha.github.io/EER-ROC/ fpr, tpr, thresholds = roc_curve(labels.flatten(), preds.flatten()) eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.) return loss, eer1234567891011121314151617181920212223242526272829
## Mel-filterbankmel_window_length = 25 # In millisecondsmel_window_step = 10 # In millisecondsmel_n_channels = 40
## Audiosampling_rate = 16000# Number of spectrogram frames in a partial utterancepartials_n_frames = 160 # 1600 ms# Number of spectrogram frames at inferenceinference_n_frames = 80 # 800 ms
## Voice Activation Detection# Window size of the VAD. Must be either 10, 20 or 30 milliseconds.# This sets the granularity of the VAD. Should not need to be changed.vad_window_length = 30 # In milliseconds# Number of frames to average together when performing the moving average smoothing.# The larger this value, the larger the VAD variations must be to not get smoothed out. vad_moving_average_width = 8# Maximum number of consecutive silent frames a segment can have.vad_max_silence_length = 6
## Audio volume normalizationaudio_norm_target_dBFS = -30
1234567891011
## Model parametersmodel_hidden_size = 256model_embedding_size = 256model_num_layers = 3
## Training parameterslearning_rate_init = 1e-4speakers_per_batch = 64utterances_per_speaker = 10123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285from multiprocess.pool import ThreadPoolfrom speaker_encoder.params_data import *from speaker_encoder.config import librispeech_datasets, anglophone_nationalitesfrom datetime import datetimefrom speaker_encoder import audiofrom pathlib import Pathfrom tqdm import tqdmimport numpy as np
class DatasetLog: """ Registers metadata about the dataset in a text file. """ def __init__(self, root, name): self.text_file = open(Path(root, "Log_%s.txt" % name.replace("/", "_")), "w") self.sample_data = dict() start_time = str(datetime.now().strftime("%A %d %B %Y at %H:%M")) self.write_line("Creating dataset %s on %s" % (name, start_time)) self.write_line("-----") self._log_params() def _log_params(self): from speaker_encoder import params_data self.write_line("Parameter values:") for param_name in (p for p in dir(params_data) if not p.startswith("__")): value = getattr(params_data, param_name) self.write_line("\t%s: %s" % (param_name, value)) self.write_line("-----") def write_line(self, line): self.text_file.write("%s\n" % line) def add_sample(self, **kwargs): for param_name, value in kwargs.items(): if not param_name in self.sample_data: self.sample_data[param_name] = [] self.sample_data[param_name].append(value) def finalize(self): self.write_line("Statistics:") for param_name, values in self.sample_data.items(): self.write_line("\t%s:" % param_name) self.write_line("\t\tmin %.3f, max %.3f" % (np.min(values), np.max(values))) self.write_line("\t\tmean %.3f, median %.3f" % (np.mean(values), np.median(values))) self.write_line("-----") end_time = str(datetime.now().strftime("%A %d %B %Y at %H:%M")) self.write_line("Finished on %s" % end_time) self.text_file.close() def _init_preprocess_dataset(dataset_name, datasets_root, out_dir) -> (Path, DatasetLog): dataset_root = datasets_root.joinpath(dataset_name) if not dataset_root.exists(): print("Couldn\'t find %s, skipping this dataset." % dataset_root) return None, None return dataset_root, DatasetLog(out_dir, dataset_name)
def _preprocess_speaker_dirs(speaker_dirs, dataset_name, datasets_root, out_dir, extension, skip_existing, logger): print("%s: Preprocessing data for %d speakers." % (dataset_name, len(speaker_dirs))) # Function to preprocess utterances for one speaker def preprocess_speaker(speaker_dir: Path): # Give a name to the speaker that includes its dataset speaker_name = "_".join(speaker_dir.relative_to(datasets_root).parts) # Create an output directory with that name, as well as a txt file containing a # reference to each source file. speaker_out_dir = out_dir.joinpath(speaker_name) speaker_out_dir.mkdir(exist_ok=True) sources_fpath = speaker_out_dir.joinpath("_sources.txt") # There's a possibility that the preprocessing was interrupted earlier, check if # there already is a sources file. if sources_fpath.exists(): try: with sources_fpath.open("r") as sources_file: existing_fnames = {line.split(",")[0] for line in sources_file} except: existing_fnames = {} else: existing_fnames = {} # Gather all audio files for that speaker recursively sources_file = sources_fpath.open("a" if skip_existing else "w") for in_fpath in speaker_dir.glob("**/*.%s" % extension): # Check if the target output file already exists out_fname = "_".join(in_fpath.relative_to(speaker_dir).parts) out_fname = out_fname.replace(".%s" % extension, ".npy") if skip_existing and out_fname in existing_fnames: continue # Load and preprocess the waveform wav = audio.preprocess_wav(in_fpath) if len(wav) == 0: continue # Create the mel spectrogram, discard those that are too short frames = audio.wav_to_mel_spectrogram(wav) if len(frames) < partials_n_frames: continue out_fpath = speaker_out_dir.joinpath(out_fname) np.save(out_fpath, frames) logger.add_sample(duration=len(wav) / sampling_rate) sources_file.write("%s,%s\n" % (out_fname, in_fpath)) sources_file.close() # Process the utterances for each speaker with ThreadPool(8) as pool: list(tqdm(pool.imap(preprocess_speaker, speaker_dirs), dataset_name, len(speaker_dirs), unit="speakers")) logger.finalize() print("Done preprocessing %s.\n" % dataset_name)
# Function to preprocess utterances for one speakerdef __preprocess_speaker(speaker_dir: Path, datasets_root: Path, out_dir: Path, extension: str, skip_existing: bool): # Give a name to the speaker that includes its dataset speaker_name = "_".join(speaker_dir.relative_to(datasets_root).parts) # Create an output directory with that name, as well as a txt file containing a # reference to each source file. speaker_out_dir = out_dir.joinpath(speaker_name) speaker_out_dir.mkdir(exist_ok=True) sources_fpath = speaker_out_dir.joinpath("_sources.txt") # There's a possibility that the preprocessing was interrupted earlier, check if # there already is a sources file. # if sources_fpath.exists(): # try: # with sources_fpath.open("r") as sources_file: # existing_fnames = {line.split(",")[0] for line in sources_file} # except: # existing_fnames = {} # else: # existing_fnames = {} existing_fnames = {} # Gather all audio files for that speaker recursively sources_file = sources_fpath.open("a" if skip_existing else "w")
for in_fpath in speaker_dir.glob("**/*.%s" % extension): # Check if the target output file already exists out_fname = "_".join(in_fpath.relative_to(speaker_dir).parts) out_fname = out_fname.replace(".%s" % extension, ".npy") if skip_existing and out_fname in existing_fnames: continue # Load and preprocess the waveform wav = audio.preprocess_wav(in_fpath) if len(wav) == 0: continue # Create the mel spectrogram, discard those that are too short frames = audio.wav_to_mel_spectrogram(wav) if len(frames) < partials_n_frames: continue out_fpath = speaker_out_dir.joinpath(out_fname) np.save(out_fpath, frames) # logger.add_sample(duration=len(wav) / sampling_rate) sources_file.write("%s,%s\n" % (out_fname, in_fpath)) sources_file.close() return len(wav)
def _preprocess_speaker_dirs_vox2(speaker_dirs, dataset_name, datasets_root, out_dir, extension, skip_existing, logger): # from multiprocessing import Pool, cpu_count from pathos.multiprocessing import ProcessingPool as Pool # Function to preprocess utterances for one speaker def __preprocess_speaker(speaker_dir: Path): # Give a name to the speaker that includes its dataset speaker_name = "_".join(speaker_dir.relative_to(datasets_root).parts) # Create an output directory with that name, as well as a txt file containing a # reference to each source file. speaker_out_dir = out_dir.joinpath(speaker_name) speaker_out_dir.mkdir(exist_ok=True) sources_fpath = speaker_out_dir.joinpath("_sources.txt") existing_fnames = {} # Gather all audio files for that speaker recursively sources_file = sources_fpath.open("a" if skip_existing else "w") wav_lens = [] for in_fpath in speaker_dir.glob("**/*.%s" % extension): # Check if the target output file already exists out_fname = "_".join(in_fpath.relative_to(speaker_dir).parts) out_fname = out_fname.replace(".%s" % extension, ".npy") if skip_existing and out_fname in existing_fnames: continue # Load and preprocess the waveform wav = audio.preprocess_wav(in_fpath) if len(wav) == 0: continue # Create the mel spectrogram, discard those that are too short frames = audio.wav_to_mel_spectrogram(wav) if len(frames) < partials_n_frames: continue out_fpath = speaker_out_dir.joinpath(out_fname) np.save(out_fpath, frames) # logger.add_sample(duration=len(wav) / sampling_rate) sources_file.write("%s,%s\n" % (out_fname, in_fpath)) wav_lens.append(len(wav)) sources_file.close() return wav_lens
print("%s: Preprocessing data for %d speakers." % (dataset_name, len(speaker_dirs))) # Process the utterances for each speaker # with ThreadPool(8) as pool: # list(tqdm(pool.imap(preprocess_speaker, speaker_dirs), dataset_name, len(speaker_dirs), # unit="speakers")) pool = Pool(processes=20) for i, wav_lens in enumerate(pool.map(__preprocess_speaker, speaker_dirs), 1): for wav_len in wav_lens: logger.add_sample(duration=wav_len / sampling_rate) print(f'{i}/{len(speaker_dirs)} \r')
logger.finalize() print("Done preprocessing %s.\n" % dataset_name)
def preprocess_librispeech(datasets_root: Path, out_dir: Path, skip_existing=False): for dataset_name in librispeech_datasets["train"]["other"]: # Initialize the preprocessing dataset_root, logger = _init_preprocess_dataset(dataset_name, datasets_root, out_dir) if not dataset_root: return # Preprocess all speakers speaker_dirs = list(dataset_root.glob("*")) _preprocess_speaker_dirs(speaker_dirs, dataset_name, datasets_root, out_dir, "flac", skip_existing, logger)
def preprocess_voxceleb1(datasets_root: Path, out_dir: Path, skip_existing=False): # Initialize the preprocessing dataset_name = "VoxCeleb1" dataset_root, logger = _init_preprocess_dataset(dataset_name, datasets_root, out_dir) if not dataset_root: return
# Get the contents of the meta file with dataset_root.joinpath("vox1_meta.csv").open("r") as metafile: metadata = [line.split("\t") for line in metafile][1:] # Select the ID and the nationality, filter out non-anglophone speakers nationalities = {line[0]: line[3] for line in metadata} # keep_speaker_ids = [speaker_id for speaker_id, nationality in nationalities.items() if # nationality.lower() in anglophone_nationalites] keep_speaker_ids = [speaker_id for speaker_id, nationality in nationalities.items()] print("VoxCeleb1: using samples from %d (presumed anglophone) speakers out of %d." % (len(keep_speaker_ids), len(nationalities))) # Get the speaker directories for anglophone speakers only speaker_dirs = dataset_root.joinpath("wav").glob("*") speaker_dirs = [speaker_dir for speaker_dir in speaker_dirs if speaker_dir.name in keep_speaker_ids] print("VoxCeleb1: found %d anglophone speakers on the disk, %d missing (this is normal)." % (len(speaker_dirs), len(keep_speaker_ids) - len(speaker_dirs)))
# Preprocess all speakers _preprocess_speaker_dirs(speaker_dirs, dataset_name, datasets_root, out_dir, "wav", skip_existing, logger)
def preprocess_voxceleb2(datasets_root: Path, out_dir: Path, skip_existing=False): # Initialize the preprocessing dataset_name = "VoxCeleb2" dataset_root, logger = _init_preprocess_dataset(dataset_name, datasets_root, out_dir) if not dataset_root: return # Get the speaker directories # Preprocess all speakers speaker_dirs = list(dataset_root.joinpath("dev", "aac").glob("*")) _preprocess_speaker_dirs_vox2(speaker_dirs, dataset_name, datasets_root, out_dir, "m4a", skip_existing, logger)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125from speaker_encoder.visualizations import Visualizationsfrom speaker_encoder.data_objects import SpeakerVerificationDataLoader, SpeakerVerificationDatasetfrom speaker_encoder.params_model import *from speaker_encoder.model import SpeakerEncoderfrom utils.profiler import Profilerfrom pathlib import Pathimport torch
def sync(device: torch.device): # FIXME return # For correct profiling (cuda operations are async) if device.type == "cuda": torch.cuda.synchronize(device)
def train(run_id: str, clean_data_root: Path, models_dir: Path, umap_every: int, save_every: int, backup_every: int, vis_every: int, force_restart: bool, visdom_server: str, no_visdom: bool): # Create a dataset and a dataloader dataset = SpeakerVerificationDataset(clean_data_root) loader = SpeakerVerificationDataLoader( dataset, speakers_per_batch, # 64 utterances_per_speaker, # 10 num_workers=8, ) # Setup the device on which to run the forward pass and the loss. These can be different, # because the forward pass is faster on the GPU whereas the loss is often (depending on your # hyperparameters) faster on the CPU. device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # FIXME: currently, the gradient is None if loss_device is cuda loss_device = torch.device("cpu") # Create the model and the optimizer model = SpeakerEncoder(device, loss_device) optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate_init) init_step = 1 # Configure file path for the model state_fpath = models_dir.joinpath(run_id + ".pt") backup_dir = models_dir.joinpath(run_id + "_backups")
# Load any existing model if not force_restart: if state_fpath.exists(): print("Found existing model \"%s\", loading it and resuming training." % run_id) checkpoint = torch.load(state_fpath) init_step = checkpoint["step"] model.load_state_dict(checkpoint["model_state"]) optimizer.load_state_dict(checkpoint["optimizer_state"]) optimizer.param_groups[0]["lr"] = learning_rate_init else: print("No model \"%s\" found, starting training from scratch." % run_id) else: print("Starting the training from scratch.") model.train() # Initialize the visualization environment vis = Visualizations(run_id, vis_every, server=visdom_server, disabled=no_visdom) vis.log_dataset(dataset) vis.log_params() device_name = str(torch.cuda.get_device_name(0) if torch.cuda.is_available() else "CPU") vis.log_implementation({"Device": device_name}) # Training loop profiler = Profiler(summarize_every=10, disabled=False) for step, speaker_batch in enumerate(loader, init_step): profiler.tick("Blocking, waiting for batch (threaded)") # Forward pass inputs = torch.from_numpy(speaker_batch.data).to(device) sync(device) profiler.tick("Data to %s" % device) embeds = model(inputs) sync(device) profiler.tick("Forward pass") embeds_loss = embeds.view((speakers_per_batch, utterances_per_speaker, -1)).to(loss_device) loss, eer = model.loss(embeds_loss) sync(loss_device) profiler.tick("Loss")
# Backward pass model.zero_grad() loss.backward() profiler.tick("Backward pass") model.do_gradient_ops() optimizer.step() profiler.tick("Parameter update") # Update visualizations # learning_rate = optimizer.param_groups[0]["lr"] vis.update(loss.item(), eer, step) # Draw projections and save them to the backup folder if umap_every != 0 and step % umap_every == 0: print("Drawing and saving projections (step %d)" % step) backup_dir.mkdir(exist_ok=True) projection_fpath = backup_dir.joinpath("%s_umap_%06d.png" % (run_id, step)) embeds = embeds.detach().cpu().numpy() vis.draw_projections(embeds, utterances_per_speaker, step, projection_fpath) vis.save()
# Overwrite the latest version of the model if save_every != 0 and step % save_every == 0: print("Saving the model (step %d)" % step) torch.save({ "step": step + 1, "model_state": model.state_dict(), "optimizer_state": optimizer.state_dict(), }, state_fpath) # Make a backup if backup_every != 0 and step % backup_every == 0: print("Making a backup (step %d)" % step) backup_dir.mkdir(exist_ok=True) backup_fpath = backup_dir.joinpath("%s_bak_%06d.pt" % (run_id, step)) torch.save({ "step": step + 1, "model_state": model.state_dict(), "optimizer_state": optimizer.state_dict(), }, backup_fpath) profiler.tick("Extras (visualizations, saving)") 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178from speaker_encoder.data_objects.speaker_verification_dataset import SpeakerVerificationDatasetfrom datetime import datetimefrom time import perf_counter as timerimport matplotlib.pyplot as pltimport numpy as np# import webbrowserimport visdomimport umap
colormap = np.array([ [76, 255, 0], [0, 127, 70], [255, 0, 0], [255, 217, 38], [0, 135, 255], [165, 0, 165], [255, 167, 255], [0, 255, 255], [255, 96, 38], [142, 76, 0], [33, 0, 127], [0, 0, 0], [183, 183, 183],], dtype=np.float) / 255
class Visualizations: def __init__(self, env_name=None, update_every=10, server="http://localhost", disabled=False): # Tracking data self.last_update_timestamp = timer() self.update_every = update_every self.step_times = [] self.losses = [] self.eers = [] print("Updating the visualizations every %d steps." % update_every) # If visdom is disabled TODO: use a better paradigm for that self.disabled = disabled if self.disabled: return # Set the environment name now = str(datetime.now().strftime("%d-%m %Hh%M")) if env_name is None: self.env_name = now else: self.env_name = "%s (%s)" % (env_name, now) # Connect to visdom and open the corresponding window in the browser try: self.vis = visdom.Visdom(server, env=self.env_name, raise_exceptions=True) except ConnectionError: raise Exception("No visdom server detected. Run the command \"visdom\" in your CLI to " "start it.") # webbrowser.open("http://localhost:8097/env/" + self.env_name) # Create the windows self.loss_win = None self.eer_win = None # self.lr_win = None self.implementation_win = None self.projection_win = None self.implementation_string = "" def log_params(self): if self.disabled: return from speaker_encoder import params_data from speaker_encoder import params_model param_string = "<b>Model parameters</b>:<br>" for param_name in (p for p in dir(params_model) if not p.startswith("__")): value = getattr(params_model, param_name) param_string += "\t%s: %s<br>" % (param_name, value) param_string += "<b>Data parameters</b>:<br>" for param_name in (p for p in dir(params_data) if not p.startswith("__")): value = getattr(params_data, param_name) param_string += "\t%s: %s<br>" % (param_name, value) self.vis.text(param_string, opts={"title": "Parameters"}) def log_dataset(self, dataset: SpeakerVerificationDataset): if self.disabled: return dataset_string = "" dataset_string += "<b>Speakers</b>: %s\n" % len(dataset.speakers) dataset_string += "\n" + dataset.get_logs() dataset_string = dataset_string.replace("\n", "<br>") self.vis.text(dataset_string, opts={"title": "Dataset"}) def log_implementation(self, params): if self.disabled: return implementation_string = "" for param, value in params.items(): implementation_string += "<b>%s</b>: %s\n" % (param, value) implementation_string = implementation_string.replace("\n", "<br>") self.implementation_string = implementation_string self.implementation_win = self.vis.text( implementation_string, opts={"title": "Training implementation"} )
def update(self, loss, eer, step): # Update the tracking data now = timer() self.step_times.append(1000 * (now - self.last_update_timestamp)) self.last_update_timestamp = now self.losses.append(loss) self.eers.append(eer) print(".", end="") # Update the plots every <update_every> steps if step % self.update_every != 0: return time_string = "Step time: mean: %5dms std: %5dms" % \ (int(np.mean(self.step_times)), int(np.std(self.step_times))) print("\nStep %6d Loss: %.4f EER: %.4f %s" % (step, np.mean(self.losses), np.mean(self.eers), time_string)) if not self.disabled: self.loss_win = self.vis.line( [np.mean(self.losses)], [step], win=self.loss_win, update="append" if self.loss_win else None, opts=dict( legend=["Avg. loss"], xlabel="Step", ylabel="Loss", title="Loss", ) ) self.eer_win = self.vis.line( [np.mean(self.eers)], [step], win=self.eer_win, update="append" if self.eer_win else None, opts=dict( legend=["Avg. EER"], xlabel="Step", ylabel="EER", title="Equal error rate" ) ) if self.implementation_win is not None: self.vis.text( self.implementation_string + ("<b>%s</b>" % time_string), win=self.implementation_win, opts={"title": "Training implementation"}, )
# Reset the tracking self.losses.clear() self.eers.clear() self.step_times.clear() def draw_projections(self, embeds, utterances_per_speaker, step, out_fpath=None, max_speakers=10): max_speakers = min(max_speakers, len(colormap)) embeds = embeds[:max_speakers * utterances_per_speaker] n_speakers = len(embeds) // utterances_per_speaker ground_truth = np.repeat(np.arange(n_speakers), utterances_per_speaker) colors = [colormap[i] for i in ground_truth] reducer = umap.UMAP() projected = reducer.fit_transform(embeds) plt.scatter(projected[:, 0], projected[:, 1], c=colors) plt.gca().set_aspect("equal", "datalim") plt.title("UMAP projection (step %d)" % step) if not self.disabled: self.projection_win = self.vis.matplot(plt, win=self.projection_win) if out_fpath is not None: plt.savefig(out_fpath) plt.clf() def save(self): if not self.disabled: self.vis.save([self.env_name]) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173from speaker_encoder.hparams import *from speaker_encoder import audiofrom pathlib import Pathfrom typing import Union, Listfrom torch import nnfrom time import perf_counter as timerimport numpy as npimport torch
class SpeakerEncoder(nn.Module): def __init__(self, weights_fpath, device: Union[str, torch.device]=None, verbose=True): """ :param device: either a torch device or the name of a torch device (e.g. "cpu", "cuda"). If None, defaults to cuda if it is available on your machine, otherwise the model will run on cpu. Outputs are always returned on the cpu, as numpy arrays. """ super().__init__() # Define the network self.lstm = nn.LSTM(mel_n_channels, model_hidden_size, model_num_layers, batch_first=True) self.linear = nn.Linear(model_hidden_size, model_embedding_size) self.relu = nn.ReLU() # Get the target device if device is None: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") elif isinstance(device, str): device = torch.device(device) self.device = device # Load the pretrained model'speaker weights # weights_fpath = Path(__file__).resolve().parent.joinpath("pretrained.pt") # if not weights_fpath.exists(): # raise Exception("Couldn't find the voice encoder pretrained model at %s." % # weights_fpath)
start = timer() checkpoint = torch.load(weights_fpath, map_location="cpu")
self.load_state_dict(checkpoint["model_state"], strict=False) self.to(device) if verbose: print("Loaded the voice encoder model on %s in %.2f seconds." % (device.type, timer() - start))
def forward(self, mels: torch.FloatTensor): """ Computes the embeddings of a batch of utterance spectrograms. :param mels: a batch of mel spectrograms of same duration as a float32 tensor of shape (batch_size, n_frames, n_channels) :return: the embeddings as a float 32 tensor of shape (batch_size, embedding_size). Embeddings are positive and L2-normed, thus they lay in the range [0, 1]. """ # Pass the input through the LSTM layers and retrieve the final hidden state of the last # layer. Apply a cutoff to 0 for negative values and L2 normalize the embeddings. _, (hidden, _) = self.lstm(mels) embeds_raw = self.relu(self.linear(hidden[-1])) return embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True) @staticmethod def compute_partial_slices(n_samples: int, rate, min_coverage): """ Computes where to split an utterance waveform and its corresponding mel spectrogram to obtain partial utterances of <partials_n_frames> each. Both the waveform and the mel spectrogram slices are returned, so as to make each partial utterance waveform correspond to its spectrogram. The returned ranges may be indexing further than the length of the waveform. It is recommended that you pad the waveform with zeros up to wav_slices[-1].stop. :param n_samples: the number of samples in the waveform :param rate: how many partial utterances should occur per second. Partial utterances must cover the span of the entire utterance, thus the rate should not be lower than the inverse of the duration of a partial utterance. By default, partial utterances are 1.6s long and the minimum rate is thus 0.625. :param min_coverage: when reaching the last partial utterance, it may or may not have enough frames. If at least <min_pad_coverage> of <partials_n_frames> are present, then the last partial utterance will be considered by zero-padding the audio. Otherwise, it will be discarded. If there aren't enough frames for one partial utterance, this parameter is ignored so that the function always returns at least one slice. :return: the waveform slices and mel spectrogram slices as lists of array slices. Index respectively the waveform and the mel spectrogram with these slices to obtain the partial utterances. """ assert 0 < min_coverage <= 1 # Compute how many frames separate two partial utterances samples_per_frame = int((sampling_rate * mel_window_step / 1000)) n_frames = int(np.ceil((n_samples + 1) / samples_per_frame)) frame_step = int(np.round((sampling_rate / rate) / samples_per_frame)) assert 0 < frame_step, "The rate is too high" assert frame_step <= partials_n_frames, "The rate is too low, it should be %f at least" % \ (sampling_rate / (samples_per_frame * partials_n_frames)) # Compute the slices wav_slices, mel_slices = [], [] steps = max(1, n_frames - partials_n_frames + frame_step + 1) for i in range(0, steps, frame_step): mel_range = np.array([i, i + partials_n_frames]) wav_range = mel_range * samples_per_frame mel_slices.append(slice(*mel_range)) wav_slices.append(slice(*wav_range)) # Evaluate whether extra padding is warranted or not last_wav_range = wav_slices[-1] coverage = (n_samples - last_wav_range.start) / (last_wav_range.stop - last_wav_range.start) if coverage < min_coverage and len(mel_slices) > 1: mel_slices = mel_slices[:-1] wav_slices = wav_slices[:-1] return wav_slices, mel_slices def embed_utterance(self, wav: np.ndarray, return_partials=False, rate=1.3, min_coverage=0.75): """ Computes an embedding for a single utterance. The utterance is divided in partial utterances and an embedding is computed for each. The complete utterance embedding is the L2-normed average embedding of the partial utterances. TODO: independent batched version of this function :param wav: a preprocessed utterance waveform as a numpy array of float32 :param return_partials: if True, the partial embeddings will also be returned along with the wav slices corresponding to each partial utterance. :param rate: how many partial utterances should occur per second. Partial utterances must cover the span of the entire utterance, thus the rate should not be lower than the inverse of the duration of a partial utterance. By default, partial utterances are 1.6s long and the minimum rate is thus 0.625. :param min_coverage: when reaching the last partial utterance, it may or may not have enough frames. If at least <min_pad_coverage> of <partials_n_frames> are present, then the last partial utterance will be considered by zero-padding the audio. Otherwise, it will be discarded. If there aren't enough frames for one partial utterance, this parameter is ignored so that the function always returns at least one slice. :return: the embedding as a numpy array of float32 of shape (model_embedding_size,). If <return_partials> is True, the partial utterances as a numpy array of float32 of shape (n_partials, model_embedding_size) and the wav partials as a list of slices will also be returned. """ # Compute where to split the utterance into partials and pad the waveform with zeros if # the partial utterances cover a larger range. wav_slices, mel_slices = self.compute_partial_slices(len(wav), rate, min_coverage) max_wave_length = wav_slices[-1].stop if max_wave_length >= len(wav): wav = np.pad(wav, (0, max_wave_length - len(wav)), "constant") # Split the utterance into partials and forward them through the model mel = audio.wav_to_mel_spectrogram(wav) mels = np.array([mel[s] for s in mel_slices]) with torch.no_grad(): mels = torch.from_numpy(mels).to(self.device) partial_embeds = self(mels).cpu().numpy() # Compute the utterance embedding from the partial embeddings raw_embed = np.mean(partial_embeds, axis=0) embed = raw_embed / np.linalg.norm(raw_embed, 2) if return_partials: return embed, partial_embeds, wav_slices return embed def embed_speaker(self, wavs: List[np.ndarray], **kwargs): """ Compute the embedding of a collection of wavs (presumably from the same speaker) by averaging their embedding and L2-normalizing it. :param wavs: list of wavs a numpy arrays of float32. :param kwargs: extra arguments to embed_utterance() :return: the embedding as a numpy array of float32 of shape (model_embedding_size,). """ raw_embed = np.mean([self.embed_utterance(wav, return_partials=False, **kwargs) \ for wav in wavs], axis=0) return raw_embed / np.linalg.norm(raw_embed, 2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305import osimport sysimport argparseimport loggingimport jsonimport subprocessimport numpy as npfrom scipy.io.wavfile import readimport torchfrom torch.nn import functional as Ffrom commons import sequence_mask
MATPLOTLIB_FLAG = False
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)logger = logging
def get_cmodel(rank): checkpoint = torch.load('wavlm/WavLM-Large.pt') cfg = WavLMConfig(checkpoint['cfg']) cmodel = WavLM(cfg).cuda(rank) cmodel.load_state_dict(checkpoint['model']) cmodel.eval() return cmodel def get_content(cmodel, y): with torch.no_grad(): c = cmodel.extract_features(y.squeeze(1))[0] c = c.transpose(1, 2) return c
def get_vocoder(rank): with open("hifigan/config.json", "r") as f: config = json.load(f) config = hifigan.AttrDict(config) vocoder = hifigan.Generator(config) ckpt = torch.load("hifigan/generator_v1") vocoder.load_state_dict(ckpt["generator"]) vocoder.eval() vocoder.remove_weight_norm() vocoder.cuda(rank) return vocoder def transform(mel, height): # 68-92 #r = np.random.random() #rate = r * 0.3 + 0.85 # 0.85-1.15 #height = int(mel.size(-2) * rate) tgt = torchvision.transforms.functional.resize(mel, (height, mel.size(-1))) if height >= mel.size(-2): return tgt[:, :mel.size(-2), :] else: silence = tgt[:,-1:,:].repeat(1,mel.size(-2)-height,1) silence += torch.randn_like(silence) / 10 return torch.cat((tgt, silence), 1) def stretch(mel, width): # 0.5-2 return torchvision.transforms.functional.resize(mel, (mel.size(-2), width))
def load_checkpoint(checkpoint_path, model, optimizer=None): assert os.path.isfile(checkpoint_path) checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') iteration = checkpoint_dict['iteration'] learning_rate = checkpoint_dict['learning_rate'] if optimizer is not None: optimizer.load_state_dict(checkpoint_dict['optimizer']) saved_state_dict = checkpoint_dict['model'] if hasattr(model, 'module'): state_dict = model.module.state_dict() else: state_dict = model.state_dict() new_state_dict= {} for k, v in state_dict.items(): try: new_state_dict[k] = saved_state_dict[k] except: logger.info("%s is not in the checkpoint" % k) new_state_dict[k] = v if hasattr(model, 'module'): model.module.load_state_dict(new_state_dict) else: model.load_state_dict(new_state_dict) logger.info("Loaded checkpoint '{}' (iteration {})" .format( checkpoint_path, iteration)) return model, optimizer, learning_rate, iteration
def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path): logger.info("Saving model and optimizer state at iteration {} to {}".format( iteration, checkpoint_path)) if hasattr(model, 'module'): state_dict = model.module.state_dict() else: state_dict = model.state_dict() torch.save({'model': state_dict, 'iteration': iteration, 'optimizer': optimizer.state_dict(), 'learning_rate': learning_rate}, checkpoint_path)
def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050): for k, v in scalars.items(): writer.add_scalar(k, v, global_step) for k, v in histograms.items(): writer.add_histogram(k, v, global_step) for k, v in images.items(): writer.add_image(k, v, global_step, dataformats='HWC') for k, v in audios.items(): writer.add_audio(k, v, global_step, audio_sampling_rate)
def latest_checkpoint_path(dir_path, regex="G_*.pth"): f_list = glob.glob(os.path.join(dir_path, regex)) f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f)))) x = f_list[-1] print(x) return x
def plot_spectrogram_to_numpy(spectrogram): global MATPLOTLIB_FLAG if not MATPLOTLIB_FLAG: import matplotlib matplotlib.use("Agg") MATPLOTLIB_FLAG = True mpl_logger = logging.getLogger('matplotlib') mpl_logger.setLevel(logging.WARNING) import matplotlib.pylab as plt import numpy as np fig, ax = plt.subplots(figsize=(10,2)) im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation='none') plt.colorbar(im, ax=ax) plt.xlabel("Frames") plt.ylabel("Channels") plt.tight_layout()
fig.canvas.draw() data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) plt.close() return data
def plot_alignment_to_numpy(alignment, info=None): global MATPLOTLIB_FLAG if not MATPLOTLIB_FLAG: import matplotlib matplotlib.use("Agg") MATPLOTLIB_FLAG = True mpl_logger = logging.getLogger('matplotlib') mpl_logger.setLevel(logging.WARNING) import matplotlib.pylab as plt import numpy as np
fig, ax = plt.subplots(figsize=(6, 4)) im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower', interpolation='none') fig.colorbar(im, ax=ax) xlabel = 'Decoder timestep' if info is not None: xlabel += '\n\n' + info plt.xlabel(xlabel) plt.ylabel('Encoder timestep') plt.tight_layout()
fig.canvas.draw() data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) plt.close() return data
def load_wav_to_torch(full_path): sampling_rate, data = read(full_path) return torch.FloatTensor(data.astype(np.float32)), sampling_rate
def load_filepaths_and_text(filename, split="|"): with open(filename, encoding='utf-8') as f: filepaths_and_text = [line.strip().split(split) for line in f] return filepaths_and_text
def get_hparams(init=True): parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', type=str, default="./configs/base.json", help='JSON file for configuration') parser.add_argument('-m', '--model', type=str, required=True, help='Model name') args = parser.parse_args() model_dir = os.path.join("./logs", args.model)
if not os.path.exists(model_dir): os.makedirs(model_dir)
config_path = args.config config_save_path = os.path.join(model_dir, "config.json") if init: with open(config_path, "r") as f: data = f.read() with open(config_save_path, "w") as f: f.write(data) else: with open(config_save_path, "r") as f: data = f.read() config = json.loads(data) hparams = HParams(**config) hparams.model_dir = model_dir return hparams
def get_hparams_from_dir(model_dir): config_save_path = os.path.join(model_dir, "config.json") with open(config_save_path, "r") as f: data = f.read() config = json.loads(data)
hparams =HParams(**config) hparams.model_dir = model_dir return hparams
def get_hparams_from_file(config_path): with open(config_path, "r") as f: data = f.read() config = json.loads(data)
hparams =HParams(**config) return hparams
def check_git_hash(model_dir): source_dir = os.path.dirname(os.path.realpath(__file__)) if not os.path.exists(os.path.join(source_dir, ".git")): logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format( source_dir )) return
cur_hash = subprocess.getoutput("git rev-parse HEAD")
path = os.path.join(model_dir, "githash") if os.path.exists(path): saved_hash = open(path).read() if saved_hash != cur_hash: logger.warn("git hash values are different. {}(saved) != {}(current)".format( saved_hash[:8], cur_hash[:8])) else: open(path, "w").write(cur_hash)
def get_logger(model_dir, filename="train.log"): global logger logger = logging.getLogger(os.path.basename(model_dir)) logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s") if not os.path.exists(model_dir): os.makedirs(model_dir) h = logging.FileHandler(os.path.join(model_dir, filename)) h.setLevel(logging.DEBUG) h.setFormatter(formatter) logger.addHandler(h) return logger
class HParams(): def __init__(self, **kwargs): for k, v in kwargs.items(): if type(v) == dict: v = HParams(**v) self[k] = v def keys(self): return self.__dict__.keys()
def items(self): return self.__dict__.items()
def values(self): return self.__dict__.values()
def __len__(self): return len(self.__dict__)
def __getitem__(self, key): return getattr(self, key)
def __setitem__(self, key, value): return setattr(self, key, value)
def __contains__(self, key): return key in self.__dict__
def __repr__(self): return self.__dict__.__repr__().gitattributesAdded+34
.gitignoreAdded+2
README.mdAdded+14
app.pyAdded+103
checkpoints/freevc-24.pthAdded+3
checkpoints/freevc-s.pthAdded+3
checkpoints/freevc.pthAdded+3
commons.pyAdded+171
configs/freevc-24.jsonAdded+54
configs/freevc-s.jsonAdded+54
configs/freevc.jsonAdded+54
mel_processing.pyAdded+112
models.pyAdded+351
modules.pyAdded+342
p225_001.wavAdded
p226_002.wavAdded
requirements.txtAdded+7
speaker_encoder/__init__.pyAdded
speaker_encoder/audio.pyAdded+107
speaker_encoder/ckpt/pretrained_bak_5805000.ptAdded+3
speaker_encoder/compute_embed.pyAdded+40
speaker_encoder/config.pyAdded+45
speaker_encoder/data_objects/__init__.pyAdded+2
speaker_encoder/data_objects/random_cycler.pyAdded+37
speaker_encoder/data_objects/speaker.pyAdded+40
speaker_encoder/data_objects/speaker_batch.pyAdded+12
speaker_encoder/data_objects/speaker_verification_dataset.pyAdded+56
speaker_encoder/data_objects/utterance.pyAdded+26
speaker_encoder/hparams.pyAdded+31
speaker_encoder/inference.pyAdded+177
speaker_encoder/model.pyAdded+135
speaker_encoder/params_data.pyAdded+29
speaker_encoder/params_model.pyAdded+11
speaker_encoder/preprocess.pyAdded+285
speaker_encoder/train.pyAdded+125
speaker_encoder/visualizations.pyAdded+178
speaker_encoder/voice_encoder.pyAdded+173
utils.pyAdded+305