id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
17,606 | import torch
import torch.nn as nn
import functools
import torch.nn.functional as F
def hinge_d_loss(logits_real, logits_fake):
loss_real = torch.mean(F.relu(1.0 - logits_real))
loss_fake = torch.mean(F.relu(1.0 + logits_fake))
d_loss = 0.5 * (loss_real + loss_fake)
return d_loss | null |
17,607 | import torch
import torch.nn as nn
import functools
import torch.nn.functional as F
def vanilla_d_loss(logits_real, logits_fake):
d_loss = 0.5 * (
torch.mean(F.softplus(-logits_real)) + torch.mean(F.softplus(logits_fake))
)
return d_loss | null |
17,608 | import torch
import torch.nn as nn
import functools
import torch.nn.functional as F
def adopt_weight(weight, global_step, threshold=0, value=0.0):
if global_step < threshold:
weight = value
return weight | null |
17,609 | import torch
import torch.nn as nn
import functools
import torch.nn.functional as F
def weights_init(m):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find("BatchNorm") != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0) | null |
17,610 | import torch
import torch.nn as nn
import torch.nn.functional as F
from modules.distributions.distributions import DiagonalGaussianDistribution
def nonlinearity(x):
# swish
return x * torch.sigmoid(x) | null |
17,611 | import torch
import torch.nn as nn
import torch.nn.functional as F
from modules.distributions.distributions import DiagonalGaussianDistribution
def Normalize(in_channels):
return torch.nn.GroupNorm(
num_groups=32, num_channels=in_channels, eps=1e-6, affine=True
) | null |
17,612 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
class CheckpointFunction(torch.autograd.Function):
def forward(ctx, run_function, length, *args):
ctx.run_function = run_function
ctx.input_tensors = list(args[:length])
ctx.input_params = list(args[length:])
with torch.no_grad():
output_tensors = ctx.run_function(*ctx.input_tensors)
return output_tensors
def backward(ctx, *output_grads):
ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
with torch.enable_grad():
# Fixes a bug where the first op in run_function modifies the
# Tensor storage in place, which is not allowed for detach()'d
# Tensors.
shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
output_tensors = ctx.run_function(*shallow_copies)
input_grads = torch.autograd.grad(
output_tensors,
ctx.input_tensors + ctx.input_params,
output_grads,
allow_unused=True,
)
del ctx.input_tensors
del ctx.input_params
del output_tensors
return (None, None) + input_grads
The provided code snippet includes necessary dependencies for implementing the `checkpoint` function. Write a Python function `def checkpoint(func, inputs, params, flag)` to solve the following problem:
Evaluate a function without caching intermediate activations, allowing for reduced memory at the expense of extra compute in the backward pass. :param func: the function to evaluate. :param inputs: the argument sequence to pass to `func`. :param params: a sequence of parameters `func` depends on but does not explicitly take as arguments. :param flag: if False, disable gradient checkpointing.
Here is the function:
def checkpoint(func, inputs, params, flag):
"""
Evaluate a function without caching intermediate activations, allowing for
reduced memory at the expense of extra compute in the backward pass.
:param func: the function to evaluate.
:param inputs: the argument sequence to pass to `func`.
:param params: a sequence of parameters `func` depends on but does not
explicitly take as arguments.
:param flag: if False, disable gradient checkpointing.
"""
if flag:
args = tuple(inputs) + tuple(params)
return CheckpointFunction.apply(func, len(inputs), *args)
else:
return func(*inputs) | Evaluate a function without caching intermediate activations, allowing for reduced memory at the expense of extra compute in the backward pass. :param func: the function to evaluate. :param inputs: the argument sequence to pass to `func`. :param params: a sequence of parameters `func` depends on but does not explicitly take as arguments. :param flag: if False, disable gradient checkpointing. |
17,613 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
def uniq(arr):
return {el: True for el in arr}.keys() | null |
17,614 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
def exists(val):
return val is not None
def default(val, d):
if exists(val):
return val
return d() if isfunction(d) else d | null |
17,615 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
def max_neg_value(t):
return -torch.finfo(t.dtype).max | null |
17,616 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
def init_(tensor):
dim = tensor.shape[-1]
std = 1 / math.sqrt(dim)
tensor.uniform_(-std, std)
return tensor | null |
17,617 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
The provided code snippet includes necessary dependencies for implementing the `zero_module` function. Write a Python function `def zero_module(module)` to solve the following problem:
Zero out the parameters of a module and return it.
Here is the function:
def zero_module(module):
"""
Zero out the parameters of a module and return it.
"""
for p in module.parameters():
p.detach().zero_()
return module | Zero out the parameters of a module and return it. |
17,618 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
def Normalize(in_channels):
return torch.nn.GroupNorm(
num_groups=32, num_channels=in_channels, eps=1e-6, affine=True
) | null |
17,619 | from abc import abstractmethod
from functools import partial
import math
from typing import Iterable
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import repeat
from models.tta.ldm.attention import SpatialTransformer
class CheckpointFunction(torch.autograd.Function):
def forward(ctx, run_function, length, *args):
ctx.run_function = run_function
ctx.input_tensors = list(args[:length])
ctx.input_params = list(args[length:])
with torch.no_grad():
output_tensors = ctx.run_function(*ctx.input_tensors)
return output_tensors
def backward(ctx, *output_grads):
ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
with torch.enable_grad():
# Fixes a bug where the first op in run_function modifies the
# Tensor storage in place, which is not allowed for detach()'d
# Tensors.
shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
output_tensors = ctx.run_function(*shallow_copies)
input_grads = torch.autograd.grad(
output_tensors,
ctx.input_tensors + ctx.input_params,
output_grads,
allow_unused=True,
)
del ctx.input_tensors
del ctx.input_params
del output_tensors
return (None, None) + input_grads
The provided code snippet includes necessary dependencies for implementing the `checkpoint` function. Write a Python function `def checkpoint(func, inputs, params, flag)` to solve the following problem:
Evaluate a function without caching intermediate activations, allowing for reduced memory at the expense of extra compute in the backward pass. :param func: the function to evaluate. :param inputs: the argument sequence to pass to `func`. :param params: a sequence of parameters `func` depends on but does not explicitly take as arguments. :param flag: if False, disable gradient checkpointing.
Here is the function:
def checkpoint(func, inputs, params, flag):
"""
Evaluate a function without caching intermediate activations, allowing for
reduced memory at the expense of extra compute in the backward pass.
:param func: the function to evaluate.
:param inputs: the argument sequence to pass to `func`.
:param params: a sequence of parameters `func` depends on but does not
explicitly take as arguments.
:param flag: if False, disable gradient checkpointing.
"""
if flag:
args = tuple(inputs) + tuple(params)
return CheckpointFunction.apply(func, len(inputs), *args)
else:
return func(*inputs) | Evaluate a function without caching intermediate activations, allowing for reduced memory at the expense of extra compute in the backward pass. :param func: the function to evaluate. :param inputs: the argument sequence to pass to `func`. :param params: a sequence of parameters `func` depends on but does not explicitly take as arguments. :param flag: if False, disable gradient checkpointing. |
17,620 | from abc import abstractmethod
from functools import partial
import math
from typing import Iterable
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import repeat
from models.tta.ldm.attention import SpatialTransformer
The provided code snippet includes necessary dependencies for implementing the `zero_module` function. Write a Python function `def zero_module(module)` to solve the following problem:
Zero out the parameters of a module and return it.
Here is the function:
def zero_module(module):
"""
Zero out the parameters of a module and return it.
"""
for p in module.parameters():
p.detach().zero_()
return module | Zero out the parameters of a module and return it. |
17,621 | from abc import abstractmethod
from functools import partial
import math
from typing import Iterable
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import repeat
from models.tta.ldm.attention import SpatialTransformer
The provided code snippet includes necessary dependencies for implementing the `timestep_embedding` function. Write a Python function `def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False)` to solve the following problem:
Create sinusoidal timestep embeddings. :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an [N x dim] Tensor of positional embeddings.
Here is the function:
def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
"""
Create sinusoidal timestep embeddings.
:param timesteps: a 1-D Tensor of N indices, one per batch element.
These may be fractional.
:param dim: the dimension of the output.
:param max_period: controls the minimum frequency of the embeddings.
:return: an [N x dim] Tensor of positional embeddings.
"""
if not repeat_only:
half = dim // 2
freqs = torch.exp(
-math.log(max_period)
* torch.arange(start=0, end=half, dtype=torch.float32)
/ half
).to(device=timesteps.device)
args = timesteps[:, None].float() * freqs[None]
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
if dim % 2:
embedding = torch.cat(
[embedding, torch.zeros_like(embedding[:, :1])], dim=-1
)
else:
embedding = repeat(timesteps, "b -> b d", d=dim)
return embedding | Create sinusoidal timestep embeddings. :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an [N x dim] Tensor of positional embeddings. |
17,622 | from abc import abstractmethod
from functools import partial
import math
from typing import Iterable
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import repeat
from models.tta.ldm.attention import SpatialTransformer
class GroupNorm32(nn.GroupNorm):
def forward(self, x):
return super().forward(x.float()).type(x.dtype)
The provided code snippet includes necessary dependencies for implementing the `normalization` function. Write a Python function `def normalization(channels)` to solve the following problem:
Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization.
Here is the function:
def normalization(channels):
"""
Make a standard normalization layer.
:param channels: number of input channels.
:return: an nn.Module for normalization.
"""
return GroupNorm32(32, channels) | Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization. |
17,623 | from abc import abstractmethod
from functools import partial
import math
from typing import Iterable
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import repeat
from models.tta.ldm.attention import SpatialTransformer
The provided code snippet includes necessary dependencies for implementing the `count_flops_attn` function. Write a Python function `def count_flops_attn(model, _x, y)` to solve the following problem:
A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, )
Here is the function:
def count_flops_attn(model, _x, y):
"""
A counter for the `thop` package to count the operations in an
attention operation.
Meant to be used like:
macs, params = thop.profile(
model,
inputs=(inputs, timestamps),
custom_ops={QKVAttention: QKVAttention.count_flops},
)
"""
b, c, *spatial = y[0].shape
num_spatial = int(np.prod(spatial))
# We perform two matmuls with the same number of ops.
# The first computes the weight matrix, the second computes
# the combination of the value vectors.
matmul_ops = 2 * b * (num_spatial**2) * c
model.total_ops += torch.DoubleTensor([matmul_ops]) | A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) |
17,624 | from abc import abstractmethod
from functools import partial
import math
from typing import Iterable
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import repeat
from models.tta.ldm.attention import SpatialTransformer
The provided code snippet includes necessary dependencies for implementing the `conv_nd` function. Write a Python function `def conv_nd(dims, *args, **kwargs)` to solve the following problem:
Create a 1D, 2D, or 3D convolution module.
Here is the function:
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return nn.Conv2d(*args, **kwargs)
elif dims == 3:
return nn.Conv3d(*args, **kwargs)
raise ValueError(f"unsupported dimensions: {dims}") | Create a 1D, 2D, or 3D convolution module. |
17,625 | from abc import abstractmethod
from functools import partial
import math
from typing import Iterable
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import repeat
from models.tta.ldm.attention import SpatialTransformer
The provided code snippet includes necessary dependencies for implementing the `avg_pool_nd` function. Write a Python function `def avg_pool_nd(dims, *args, **kwargs)` to solve the following problem:
Create a 1D, 2D, or 3D average pooling module.
Here is the function:
def avg_pool_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D average pooling module.
"""
if dims == 1:
return nn.AvgPool1d(*args, **kwargs)
elif dims == 2:
return nn.AvgPool2d(*args, **kwargs)
elif dims == 3:
return nn.AvgPool3d(*args, **kwargs)
raise ValueError(f"unsupported dimensions: {dims}") | Create a 1D, 2D, or 3D average pooling module. |
17,626 | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
from models.tta.ldm.inference_utils.utils import get_padding, init_weights
def feature_loss(fmap_r, fmap_g):
loss = 0
for dr, dg in zip(fmap_r, fmap_g):
for rl, gl in zip(dr, dg):
loss += torch.mean(torch.abs(rl - gl))
return loss * 2 | null |
17,627 | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
from models.tta.ldm.inference_utils.utils import get_padding, init_weights
def discriminator_loss(disc_real_outputs, disc_generated_outputs):
loss = 0
r_losses = []
g_losses = []
for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
r_loss = torch.mean((1 - dr) ** 2)
g_loss = torch.mean(dg**2)
loss += r_loss + g_loss
r_losses.append(r_loss.item())
g_losses.append(g_loss.item())
return loss, r_losses, g_losses | null |
17,628 | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
from models.tta.ldm.inference_utils.utils import get_padding, init_weights
def generator_loss(disc_outputs):
loss = 0
gen_losses = []
for dg in disc_outputs:
l = torch.mean((1 - dg) ** 2)
gen_losses.append(l)
loss += l
return loss, gen_losses | null |
17,636 | import copy
import torch
from torch import nn
from torch.nn import functional as F
from utils.util import *
from modules.transformer.attentions import Encoder
from models.tts.vits.vits import ResidualCouplingBlock, PosteriorEncoder
from models.vocoders.gan.generator.bigvgan import BigVGAN
from models.vocoders.gan.generator.hifigan import HiFiGAN
from models.vocoders.gan.generator.nsfhifigan import NSFHiFiGAN
from models.vocoders.gan.generator.melgan import MelGAN
from models.vocoders.gan.generator.apnet import APNet
from modules.encoder.condition_encoder import ConditionEncoder
def slice_pitch_segments(x, ids_str, segment_size=4):
def rand_slice_segments_with_pitch(x, pitch, 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)
ret_pitch = slice_pitch_segments(pitch, ids_str, segment_size)
return ret, ret_pitch, ids_str | null |
17,637 | import math
from torch import nn
from torch.nn import functional as F
from .modules import Conv1d1x1, ResidualConv1dGLU
from .upsample import ConvInUpsampleNetwork
The provided code snippet includes necessary dependencies for implementing the `receptive_field_size` function. Write a Python function `def receptive_field_size( total_layers, num_cycles, kernel_size, dilation=lambda x: 2**x )` to solve the following problem:
Compute receptive field size Args: total_layers (int): total layers num_cycles (int): cycles kernel_size (int): kernel size dilation (lambda): lambda to compute dilation factor. ``lambda x : 1`` to disable dilated convolution. Returns: int: receptive field size in sample
Here is the function:
def receptive_field_size(
total_layers, num_cycles, kernel_size, dilation=lambda x: 2**x
):
"""Compute receptive field size
Args:
total_layers (int): total layers
num_cycles (int): cycles
kernel_size (int): kernel size
dilation (lambda): lambda to compute dilation factor. ``lambda x : 1``
to disable dilated convolution.
Returns:
int: receptive field size in sample
"""
assert total_layers % num_cycles == 0
layers_per_cycle = total_layers // num_cycles
dilations = [dilation(i % layers_per_cycle) for i in range(total_layers)]
return (kernel_size - 1) * sum(dilations) + 1 | Compute receptive field size Args: total_layers (int): total layers num_cycles (int): cycles kernel_size (int): kernel size dilation (lambda): lambda to compute dilation factor. ``lambda x : 1`` to disable dilated convolution. Returns: int: receptive field size in sample |
17,638 | import torch
import math
from torch import nn
from torch.nn import functional as F
from .conv import Conv1d as conv_Conv1d
def Conv1d(in_channels, out_channels, kernel_size, dropout=0, **kwargs):
m = conv_Conv1d(in_channels, out_channels, kernel_size, **kwargs)
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
if m.bias is not None:
nn.init.constant_(m.bias, 0)
return nn.utils.weight_norm(m)
class Conv1d(nn.Conv1d):
"""Extended nn.Conv1d for incremental dilated convolutions"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.clear_buffer()
self._linearized_weight = None
self.register_backward_hook(self._clear_linearized_weight)
def incremental_forward(self, input):
# input (B, T, C)
# run forward pre hooks
for hook in self._forward_pre_hooks.values():
hook(self, input)
# reshape weight
weight = self._get_linearized_weight()
kw = self.kernel_size[0]
dilation = self.dilation[0]
bsz = input.size(0)
if kw > 1:
input = input.data
if self.input_buffer is None:
self.input_buffer = input.new(
bsz, kw + (kw - 1) * (dilation - 1), input.size(2)
)
self.input_buffer.zero_()
else:
# shift buffer
self.input_buffer[:, :-1, :] = self.input_buffer[:, 1:, :].clone()
# append next input
self.input_buffer[:, -1, :] = input[:, -1, :]
input = self.input_buffer
if dilation > 1:
input = input[:, 0::dilation, :].contiguous()
output = F.linear(input.view(bsz, -1), weight, self.bias)
return output.view(bsz, 1, -1)
def clear_buffer(self):
self.input_buffer = None
def _get_linearized_weight(self):
if self._linearized_weight is None:
kw = self.kernel_size[0]
# nn.Conv1d
if self.weight.size() == (self.out_channels, self.in_channels, kw):
weight = self.weight.transpose(1, 2).contiguous()
else:
# fairseq.modules.conv_tbc.ConvTBC
weight = self.weight.transpose(2, 1).transpose(1, 0).contiguous()
assert weight.size() == (self.out_channels, kw, self.in_channels)
self._linearized_weight = weight.view(self.out_channels, -1)
return self._linearized_weight
def _clear_linearized_weight(self, *args):
self._linearized_weight = None
def Conv1d1x1(in_channels, out_channels, bias=True):
return Conv1d(
in_channels, out_channels, kernel_size=1, padding=0, dilation=1, bias=bias
) | null |
17,639 | import torch
import math
from torch import nn
from torch.nn import functional as F
from .conv import Conv1d as conv_Conv1d
def _conv1x1_forward(conv, x, is_incremental):
if is_incremental:
x = conv.incremental_forward(x)
else:
x = conv(x)
return x | null |
17,640 | import torch
import numpy as np
from torch import nn
from torch.nn import functional as F
def _get_activation(upsample_activation):
nonlinear = getattr(nn, upsample_activation)
return nonlinear | null |
17,641 | import os
import torch
import json
import json5
import time
import accelerate
import random
import numpy as np
import shutil
from pathlib import Path
from tqdm import tqdm
from glob import glob
from accelerate.logging import get_logger
from torch.utils.data import DataLoader
from models.vocoders.vocoder_dataset import (
VocoderDataset,
VocoderCollator,
VocoderConcatDataset,
)
from models.vocoders.gan.generator import bigvgan, hifigan, melgan, nsfhifigan, apnet
from models.vocoders.flow.waveglow import waveglow
from models.vocoders.diffusion.diffwave import diffwave
from models.vocoders.autoregressive.wavenet import wavenet
from models.vocoders.autoregressive.wavernn import wavernn
from models.vocoders.gan import gan_vocoder_inference
from models.vocoders.diffusion import diffusion_vocoder_inference
from utils.io import save_audio
_vocoder_infer_funcs = {
# "world": world_inference.synthesis_audios,
# "wavernn": wavernn_inference.synthesis_audios,
# "wavenet": wavenet_inference.synthesis_audios,
"diffwave": diffusion_vocoder_inference.synthesis_audios,
"nsfhifigan": gan_vocoder_inference.synthesis_audios,
"bigvgan": gan_vocoder_inference.synthesis_audios,
"melgan": gan_vocoder_inference.synthesis_audios,
"hifigan": gan_vocoder_inference.synthesis_audios,
"apnet": gan_vocoder_inference.synthesis_audios,
}
def load_nnvocoder(
cfg,
vocoder_name,
weights_file,
from_multi_gpu=False,
):
"""Load the specified vocoder.
cfg: the vocoder config filer.
weights_file: a folder or a .pt path.
from_multi_gpu: automatically remove the "module" string in state dicts if "True".
"""
print("Loading Vocoder from Weights file: {}".format(weights_file))
# Build model
model = _vocoders[vocoder_name](cfg)
if not os.path.isdir(weights_file):
# Load from .pt file
if vocoder_name in ["bigvgan", "hifigan", "melgan", "nsfhifigan"]:
ckpt = torch.load(
weights_file,
map_location=(
torch.device("cuda")
if torch.cuda.is_available()
else torch.device("cpu")
),
)
if from_multi_gpu:
pretrained_generator_dict = ckpt["generator_state_dict"]
generator_dict = model.state_dict()
new_generator_dict = {
k.split("module.")[-1]: v
for k, v in pretrained_generator_dict.items()
if (
k.split("module.")[-1] in generator_dict
and v.shape == generator_dict[k.split("module.")[-1]].shape
)
}
generator_dict.update(new_generator_dict)
model.load_state_dict(generator_dict)
else:
model.load_state_dict(ckpt["generator_state_dict"])
else:
model.load_state_dict(torch.load(weights_file)["state_dict"])
else:
# Load from accelerator state dict
weights_file = os.path.join(weights_file, "checkpoint")
ls = [str(i) for i in Path(weights_file).glob("*") if not "audio" in str(i)]
ls.sort(key=lambda x: int(x.split("_")[-3].split("-")[-1]), reverse=True)
checkpoint_path = ls[0]
accelerator = accelerate.Accelerator()
model = accelerator.prepare(model)
accelerator.load_state(checkpoint_path)
if torch.cuda.is_available():
model = model.cuda()
model = model.eval()
return model
def tensorize(data, device, n_samples):
"""
data: a list of numpy array
"""
assert type(data) == list
if n_samples:
data = data[:n_samples]
data = [torch.as_tensor(x, device=device) for x in data]
return data
The provided code snippet includes necessary dependencies for implementing the `synthesis` function. Write a Python function `def synthesis( cfg, vocoder_weight_file, n_samples, pred, f0s=None, batch_size=64, fast_inference=False, )` to solve the following problem:
Synthesis audios from a given vocoder and series of given features. cfg: vocoder config. vocoder_weight_file: a folder of accelerator state dict or a path to the .pt file. pred: a list of numpy arrays. [(seq_len1, acoustic_features_dim), (seq_len2, acoustic_features_dim), ...]
Here is the function:
def synthesis(
cfg,
vocoder_weight_file,
n_samples,
pred,
f0s=None,
batch_size=64,
fast_inference=False,
):
"""Synthesis audios from a given vocoder and series of given features.
cfg: vocoder config.
vocoder_weight_file: a folder of accelerator state dict or a path to the .pt file.
pred: a list of numpy arrays. [(seq_len1, acoustic_features_dim), (seq_len2, acoustic_features_dim), ...]
"""
vocoder_name = cfg.model.generator
print("Synthesis audios using {} vocoder...".format(vocoder_name))
###### TODO: World Vocoder Refactor ######
# if vocoder_name == "world":
# world_inference.synthesis_audios(
# cfg, dataset_name, split, n_samples, pred, save_dir, tag
# )
# return
# ====== Loading neural vocoder model ======
vocoder = load_nnvocoder(
cfg, vocoder_name, weights_file=vocoder_weight_file, from_multi_gpu=True
)
device = next(vocoder.parameters()).device
# ====== Inference for predicted acoustic features ======
# pred: (frame_len, n_mels) -> (n_mels, frame_len)
mels_pred = tensorize([p.T for p in pred], device, n_samples)
print("For predicted mels, #sample = {}...".format(len(mels_pred)))
audios_pred = _vocoder_infer_funcs[vocoder_name](
cfg,
vocoder,
mels_pred,
f0s=f0s,
batch_size=batch_size,
fast_inference=fast_inference,
)
return audios_pred | Synthesis audios from a given vocoder and series of given features. cfg: vocoder config. vocoder_weight_file: a folder of accelerator state dict or a path to the .pt file. pred: a list of numpy arrays. [(seq_len1, acoustic_features_dim), (seq_len2, acoustic_features_dim), ...] |
17,642 | import math
import random
from torch.utils.data import ConcatDataset, Dataset
from torch.utils.data.sampler import (
BatchSampler,
RandomSampler,
Sampler,
SequentialSampler,
)
class ScheduledSampler(Sampler):
"""A sampler that samples data from a given concat-dataset.
Args:
concat_dataset (ConcatDataset): a concatenated dataset consisting of all datasets
batch_size (int): batch size
holistic_shuffle (bool): whether to shuffle the whole dataset or not
logger (logging.Logger): logger to print warning message
Usage:
For cfg.train.batch_size = 3, cfg.train.holistic_shuffle = False, cfg.train.drop_last = True:
>>> list(ScheduledSampler(ConcatDataset([0, 1, 2], [3, 4, 5], [6, 7, 8]])))
[3, 4, 5, 0, 1, 2, 6, 7, 8]
"""
def __init__(
self, concat_dataset, batch_size, holistic_shuffle, logger=None, type="train"
):
if not isinstance(concat_dataset, ConcatDataset):
raise ValueError(
"concat_dataset must be an instance of ConcatDataset, but got {}".format(
type(concat_dataset)
)
)
if not isinstance(batch_size, int):
raise ValueError(
"batch_size must be an integer, but got {}".format(type(batch_size))
)
if not isinstance(holistic_shuffle, bool):
raise ValueError(
"holistic_shuffle must be a boolean, but got {}".format(
type(holistic_shuffle)
)
)
self.concat_dataset = concat_dataset
self.batch_size = batch_size
self.holistic_shuffle = holistic_shuffle
affected_dataset_name = []
affected_dataset_len = []
for dataset in concat_dataset.datasets:
dataset_len = len(dataset)
dataset_name = dataset.get_dataset_name()
if dataset_len < batch_size:
affected_dataset_name.append(dataset_name)
affected_dataset_len.append(dataset_len)
self.type = type
for dataset_name, dataset_len in zip(
affected_dataset_name, affected_dataset_len
):
if not type == "valid":
logger.warning(
"The {} dataset {} has a length of {}, which is smaller than the batch size {}. This may cause unexpected behavior.".format(
type, dataset_name, dataset_len, batch_size
)
)
def __len__(self):
# the number of batches with drop last
num_of_batches = sum(
[
math.floor(len(dataset) / self.batch_size)
for dataset in self.concat_dataset.datasets
]
)
return num_of_batches * self.batch_size
def __iter__(self):
iters = []
for dataset in self.concat_dataset.datasets:
iters.append(
SequentialSampler(dataset).__iter__()
if self.holistic_shuffle
else RandomSampler(dataset).__iter__()
)
init_indices = [0] + self.concat_dataset.cumulative_sizes[:-1]
output_batches = []
for dataset_idx in range(len(self.concat_dataset.datasets)):
cur_batch = []
for idx in iters[dataset_idx]:
cur_batch.append(idx + init_indices[dataset_idx])
if len(cur_batch) == self.batch_size:
output_batches.append(cur_batch)
cur_batch = []
if self.type == "valid" and len(cur_batch) > 0:
output_batches.append(cur_batch)
cur_batch = []
# force drop last in training
random.shuffle(output_batches)
output_indices = [item for sublist in output_batches for item in sublist]
return iter(output_indices)
def build_samplers(concat_dataset: Dataset, cfg, logger, type):
sampler = ScheduledSampler(
concat_dataset,
cfg.train.batch_size,
cfg.train.sampler.holistic_shuffle,
logger,
type,
)
batch_sampler = BatchSampler(
sampler,
cfg.train.batch_size,
cfg.train.sampler.drop_last if not type == "valid" else False,
)
return sampler, batch_sampler | null |
17,643 | import torch
from utils.util import pad_mels_to_tensors, pad_f0_to_tensors
def vocoder_inference(cfg, model, mels, f0s=None, device=None, fast_inference=False):
"""Inference the vocoder
Args:
mels: A tensor of mel-specs with the shape (batch_size, num_mels, frames)
Returns:
audios: A tensor of audios with the shape (batch_size, seq_len)
"""
model.eval()
with torch.no_grad():
mels = mels.to(device)
if f0s != None:
f0s = f0s.to(device)
if f0s == None and not cfg.preprocess.extract_amplitude_phase:
output = model.forward(mels)
elif cfg.preprocess.extract_amplitude_phase:
(
_,
_,
_,
_,
output,
) = model.forward(mels)
else:
output = model.forward(mels, f0s)
return output.squeeze(1).detach().cpu()
def pad_f0_to_tensors(f0s, batched=None):
# Initialize
tensors = []
if batched == None:
# Get the max frame for padding
size = -1
for f0 in f0s:
size = max(size, f0.shape[-1])
tensor = torch.zeros(len(f0s), size)
for i, f0 in enumerate(f0s):
tensor[i, : f0.shape[-1]] = f0[:]
tensors.append(tensor)
else:
start = 0
while start + batched - 1 < len(f0s):
end = start + batched - 1
# Get the max frame for padding
size = -1
for i in range(start, end + 1):
size = max(size, f0s[i].shape[-1])
tensor = torch.zeros(batched, size)
for i in range(start, end + 1):
tensor[i - start, : f0s[i].shape[-1]] = f0s[i][:]
tensors.append(tensor)
start = start + batched
if start != len(f0s):
end = len(f0s)
# Get the max frame for padding
size = -1
for i in range(start, end):
size = max(size, f0s[i].shape[-1])
tensor = torch.zeros(len(f0s) - start, size)
for i in range(start, end):
tensor[i - start, : f0s[i].shape[-1]] = f0s[i][:]
tensors.append(tensor)
return tensors
def pad_mels_to_tensors(mels, batched=None):
"""
Args:
mels: A list of mel-specs
Returns:
tensors: A list of tensors containing the batched mel-specs
mel_frames: A list of tensors containing the frames of the original mel-specs
"""
# Initialize
tensors = []
mel_frames = []
# Split mel-specs into batches to avoid cuda memory exceed
if batched == None:
# Get the max frame for padding
size = -1
for mel in mels:
size = max(size, mel.shape[-1])
tensor = torch.zeros(len(mels), mels[0].shape[0], size)
mel_frame = torch.zeros(len(mels), dtype=torch.int32)
for i, mel in enumerate(mels):
tensor[i, :, : mel.shape[-1]] = mel[:]
mel_frame[i] = mel.shape[-1]
tensors.append(tensor)
mel_frames.append(mel_frame)
else:
start = 0
while start + batched - 1 < len(mels):
end = start + batched - 1
# Get the max frame for padding
size = -1
for i in range(start, end + 1):
size = max(size, mels[i].shape[-1])
tensor = torch.zeros(batched, mels[0].shape[0], size)
mel_frame = torch.zeros(batched, dtype=torch.int32)
for i in range(start, end + 1):
tensor[i - start, :, : mels[i].shape[-1]] = mels[i][:]
mel_frame[i - start] = mels[i].shape[-1]
tensors.append(tensor)
mel_frames.append(mel_frame)
start = start + batched
if start != len(mels):
end = len(mels)
# Get the max frame for padding
size = -1
for i in range(start, end):
size = max(size, mels[i].shape[-1])
tensor = torch.zeros(len(mels) - start, mels[0].shape[0], size)
mel_frame = torch.zeros(len(mels) - start, dtype=torch.int32)
for i in range(start, end):
tensor[i - start, :, : mels[i].shape[-1]] = mels[i][:]
mel_frame[i - start] = mels[i].shape[-1]
tensors.append(tensor)
mel_frames.append(mel_frame)
return tensors, mel_frames
The provided code snippet includes necessary dependencies for implementing the `synthesis_audios` function. Write a Python function `def synthesis_audios(cfg, model, mels, f0s=None, batch_size=None, fast_inference=False)` to solve the following problem:
Inference the vocoder Args: mels: A list of mel-specs Returns: audios: A list of audios
Here is the function:
def synthesis_audios(cfg, model, mels, f0s=None, batch_size=None, fast_inference=False):
"""Inference the vocoder
Args:
mels: A list of mel-specs
Returns:
audios: A list of audios
"""
# Get the device
device = next(model.parameters()).device
audios = []
# Pad the given list into tensors
mel_batches, mel_frames = pad_mels_to_tensors(mels, batch_size)
if f0s != None:
f0_batches = pad_f0_to_tensors(f0s, batch_size)
if f0s == None:
for mel_batch, mel_frame in zip(mel_batches, mel_frames):
for i in range(mel_batch.shape[0]):
mel = mel_batch[i]
frame = mel_frame[i]
audio = vocoder_inference(
cfg,
model,
mel.unsqueeze(0),
device=device,
fast_inference=fast_inference,
).squeeze(0)
# calculate the audio length
audio_length = frame * model.cfg.preprocess.hop_size
audio = audio[:audio_length]
audios.append(audio)
else:
for mel_batch, f0_batch, mel_frame in zip(mel_batches, f0_batches, mel_frames):
for i in range(mel_batch.shape[0]):
mel = mel_batch[i]
f0 = f0_batch[i]
frame = mel_frame[i]
audio = vocoder_inference(
cfg,
model,
mel.unsqueeze(0),
f0s=f0.unsqueeze(0),
device=device,
fast_inference=fast_inference,
).squeeze(0)
# calculate the audio length
audio_length = frame * model.cfg.preprocess.hop_size
audio = audio[:audio_length]
audios.append(audio)
return audios | Inference the vocoder Args: mels: A list of mel-specs Returns: audios: A list of audios |
17,644 | import typing as tp
import torchaudio
import torch
from torch import nn
from einops import rearrange
from modules.vocoder_blocks import *
def get_2d_padding(
kernel_size: tp.Tuple[int, int], dilation: tp.Tuple[int, int] = (1, 1)
):
return (
((kernel_size[0] - 1) * dilation[0]) // 2,
((kernel_size[1] - 1) * dilation[1]) // 2,
) | null |
17,645 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.nn.utils import weight_norm
def weights_init(m):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find("BatchNorm2d") != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0) | null |
17,646 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.nn.utils import weight_norm
def WNConv1d(*args, **kwargs):
return weight_norm(nn.Conv1d(*args, **kwargs)) | null |
17,647 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.nn.utils import weight_norm
def WNConvTranspose1d(*args, **kwargs):
return weight_norm(nn.ConvTranspose1d(*args, **kwargs)) | null |
17,648 | import torchaudio
import pyworld as pw
import numpy as np
import torch
import diffsptk
import os
from tqdm import tqdm
import pickle
import json
import re
import torchaudio
from cuhkszsvc.configs.config_parse import get_wav_path, get_wav_file_path
from utils.io import has_existed
def get_mcep_params(fs):
def mcep2sp(x, mcsize, fs):
fft_size, alpha = get_mcep_params(fs)
x = torch.as_tensor(x, dtype=torch.float)
tmp = diffsptk.MelGeneralizedCepstrumToSpectrum(
alpha=alpha,
cep_order=mcsize - 1,
fft_length=fft_size,
)(x)
tmp = diffsptk.ScalarOperation("Division", 32768.0)(tmp)
sp = diffsptk.ScalarOperation("Power", 2)(tmp)
return sp.double().numpy() | null |
17,649 | import torchaudio
import pyworld as pw
import numpy as np
import torch
import diffsptk
import os
from tqdm import tqdm
import pickle
import json
import re
import torchaudio
from cuhkszsvc.configs.config_parse import get_wav_path, get_wav_file_path
from utils.io import has_existed
def sp2mcep(x, mcsize, fs):
fft_size, alpha = get_mcep_params(fs)
x = torch.as_tensor(x, dtype=torch.float)
tmp = diffsptk.ScalarOperation("SquareRoot")(x)
tmp = diffsptk.ScalarOperation("Multiplication", 32768.0)(tmp)
mgc = diffsptk.MelCepstralAnalysis(
cep_order=mcsize - 1, fft_length=fft_size, alpha=alpha, n_iter=1
)(tmp)
return mgc.numpy()
def get_world_features_of_dataset(
output_path,
dataset_path,
dataset,
dataset_type,
fs,
frameshift,
save_sp_feature=False,
):
data_dir = os.path.join(output_path, dataset)
wave_dir = get_wav_path(dataset_path, dataset)
# Dataset
dataset_file = os.path.join(data_dir, "{}.json".format(dataset_type))
if not os.path.exists(dataset_file):
print("File {} has not existed.".format(dataset_file))
return None
with open(dataset_file, "r") as f:
datasets = json.load(f)
# Save dir
f0_dir = os.path.join(output_path, dataset, "f0")
os.makedirs(f0_dir, exist_ok=True)
# Extract
f0_features = []
sp_features = []
for utt in tqdm(datasets):
wave_file = get_wav_file_path(dataset, wave_dir, utt)
f0, sp, _, _ = extract_world_features(wave_file, fs, frameshift)
sp_features.append(sp)
f0_features.append(f0)
# Save sp
if save_sp_feature:
sp_dir = os.path.join(output_path, dataset, "sp")
os.makedirs(sp_dir, exist_ok=True)
with open(os.path.join(sp_dir, "{}.pkl".format(dataset_type)), "wb") as f:
pickle.dump(sp_features, f)
# F0 statistics
f0_statistics_file = os.path.join(f0_dir, "{}_f0.pkl".format(dataset_type))
f0_statistics(f0_features, f0_statistics_file)
return sp_features
def extract_mcep_features_of_dataset(
output_path, dataset_path, dataset, mcsize, fs, frameshift, splits=None
):
output_dir = os.path.join(output_path, dataset, "mcep/{}".format(fs))
if not splits:
splits = ["train", "test"] if dataset != "m4singer" else ["test"]
for dataset_type in splits:
print("-" * 20)
print("Dataset: {}, {}".format(dataset, dataset_type))
output_file = os.path.join(output_dir, "{}.pkl".format(dataset_type))
if has_existed(output_file):
continue
# Extract SP features
print("\nExtracting SP featuers...")
sp_features = get_world_features_of_dataset(
output_path, dataset_path, dataset, dataset_type, fs, frameshift
)
# SP to MCEP
print("\nTransform SP to MCEP...")
mcep_features = [sp2mcep(sp, mcsize=mcsize, fs=fs) for sp in tqdm(sp_features)]
# Save
os.makedirs(output_dir, exist_ok=True)
with open(output_file, "wb") as f:
pickle.dump(mcep_features, f) | null |
17,650 | import torchaudio
import pyworld as pw
import numpy as np
import torch
import diffsptk
import os
from tqdm import tqdm
import pickle
import json
import re
import torchaudio
from cuhkszsvc.configs.config_parse import get_wav_path, get_wav_file_path
from utils.io import has_existed
def world_synthesis(f0, sp, ap, fs, frameshift):
y = pw.synthesize(
f0, sp, ap, fs, frame_period=frameshift
) # synthesize an utterance using the parameters
return y | null |
17,651 | import torch
import numpy as np
from tqdm import tqdm
from utils.util import pad_mels_to_tensors, pad_f0_to_tensors
def vocoder_inference(cfg, model, mels, f0s=None, device=None, fast_inference=False):
"""Inference the vocoder
Args:
mels: A tensor of mel-specs with the shape (batch_size, num_mels, frames)
Returns:
audios: A tensor of audios with the shape (batch_size, seq_len)
"""
model.eval()
with torch.no_grad():
training_noise_schedule = np.array(cfg.model.diffwave.noise_schedule)
inference_noise_schedule = (
np.array(cfg.model.diffwave.inference_noise_schedule)
if fast_inference
else np.array(cfg.model.diffwave.noise_schedule)
)
talpha = 1 - training_noise_schedule
talpha_cum = np.cumprod(talpha)
beta = inference_noise_schedule
alpha = 1 - beta
alpha_cum = np.cumprod(alpha)
T = []
for s in range(len(inference_noise_schedule)):
for t in range(len(training_noise_schedule) - 1):
if talpha_cum[t + 1] <= alpha_cum[s] <= talpha_cum[t]:
twiddle = (talpha_cum[t] ** 0.5 - alpha_cum[s] ** 0.5) / (
talpha_cum[t] ** 0.5 - talpha_cum[t + 1] ** 0.5
)
T.append(t + twiddle)
break
T = np.array(T, dtype=np.float32)
mels = mels.to(device)
audio = torch.randn(
mels.shape[0],
cfg.preprocess.hop_size * mels.shape[-1],
device=device,
)
for n in tqdm(range(len(alpha) - 1, -1, -1)):
c1 = 1 / alpha[n] ** 0.5
c2 = beta[n] / (1 - alpha_cum[n]) ** 0.5
audio = c1 * (
audio
- c2
* model(audio, torch.tensor([T[n]], device=audio.device), mels).squeeze(
1
)
)
if n > 0:
noise = torch.randn_like(audio)
sigma = (
(1.0 - alpha_cum[n - 1]) / (1.0 - alpha_cum[n]) * beta[n]
) ** 0.5
audio += sigma * noise
audio = torch.clamp(audio, -1.0, 1.0)
return audio.detach().cpu()
def pad_f0_to_tensors(f0s, batched=None):
# Initialize
tensors = []
if batched == None:
# Get the max frame for padding
size = -1
for f0 in f0s:
size = max(size, f0.shape[-1])
tensor = torch.zeros(len(f0s), size)
for i, f0 in enumerate(f0s):
tensor[i, : f0.shape[-1]] = f0[:]
tensors.append(tensor)
else:
start = 0
while start + batched - 1 < len(f0s):
end = start + batched - 1
# Get the max frame for padding
size = -1
for i in range(start, end + 1):
size = max(size, f0s[i].shape[-1])
tensor = torch.zeros(batched, size)
for i in range(start, end + 1):
tensor[i - start, : f0s[i].shape[-1]] = f0s[i][:]
tensors.append(tensor)
start = start + batched
if start != len(f0s):
end = len(f0s)
# Get the max frame for padding
size = -1
for i in range(start, end):
size = max(size, f0s[i].shape[-1])
tensor = torch.zeros(len(f0s) - start, size)
for i in range(start, end):
tensor[i - start, : f0s[i].shape[-1]] = f0s[i][:]
tensors.append(tensor)
return tensors
def pad_mels_to_tensors(mels, batched=None):
"""
Args:
mels: A list of mel-specs
Returns:
tensors: A list of tensors containing the batched mel-specs
mel_frames: A list of tensors containing the frames of the original mel-specs
"""
# Initialize
tensors = []
mel_frames = []
# Split mel-specs into batches to avoid cuda memory exceed
if batched == None:
# Get the max frame for padding
size = -1
for mel in mels:
size = max(size, mel.shape[-1])
tensor = torch.zeros(len(mels), mels[0].shape[0], size)
mel_frame = torch.zeros(len(mels), dtype=torch.int32)
for i, mel in enumerate(mels):
tensor[i, :, : mel.shape[-1]] = mel[:]
mel_frame[i] = mel.shape[-1]
tensors.append(tensor)
mel_frames.append(mel_frame)
else:
start = 0
while start + batched - 1 < len(mels):
end = start + batched - 1
# Get the max frame for padding
size = -1
for i in range(start, end + 1):
size = max(size, mels[i].shape[-1])
tensor = torch.zeros(batched, mels[0].shape[0], size)
mel_frame = torch.zeros(batched, dtype=torch.int32)
for i in range(start, end + 1):
tensor[i - start, :, : mels[i].shape[-1]] = mels[i][:]
mel_frame[i - start] = mels[i].shape[-1]
tensors.append(tensor)
mel_frames.append(mel_frame)
start = start + batched
if start != len(mels):
end = len(mels)
# Get the max frame for padding
size = -1
for i in range(start, end):
size = max(size, mels[i].shape[-1])
tensor = torch.zeros(len(mels) - start, mels[0].shape[0], size)
mel_frame = torch.zeros(len(mels) - start, dtype=torch.int32)
for i in range(start, end):
tensor[i - start, :, : mels[i].shape[-1]] = mels[i][:]
mel_frame[i - start] = mels[i].shape[-1]
tensors.append(tensor)
mel_frames.append(mel_frame)
return tensors, mel_frames
The provided code snippet includes necessary dependencies for implementing the `synthesis_audios` function. Write a Python function `def synthesis_audios(cfg, model, mels, f0s=None, batch_size=None, fast_inference=False)` to solve the following problem:
Inference the vocoder Args: mels: A list of mel-specs Returns: audios: A list of audios
Here is the function:
def synthesis_audios(cfg, model, mels, f0s=None, batch_size=None, fast_inference=False):
"""Inference the vocoder
Args:
mels: A list of mel-specs
Returns:
audios: A list of audios
"""
# Get the device
device = next(model.parameters()).device
audios = []
# Pad the given list into tensors
mel_batches, mel_frames = pad_mels_to_tensors(mels, batch_size)
if f0s != None:
f0_batches = pad_f0_to_tensors(f0s, batch_size)
if f0s == None:
for mel_batch, mel_frame in zip(mel_batches, mel_frames):
for i in range(mel_batch.shape[0]):
mel = mel_batch[i]
frame = mel_frame[i]
audio = vocoder_inference(
cfg,
model,
mel.unsqueeze(0),
device=device,
fast_inference=fast_inference,
).squeeze(0)
# calculate the audio length
audio_length = frame * cfg.preprocess.hop_size
audio = audio[:audio_length]
audios.append(audio)
else:
for mel_batch, f0_batch, mel_frame in zip(mel_batches, f0_batches, mel_frames):
for i in range(mel_batch.shape[0]):
mel = mel_batch[i]
f0 = f0_batch[i]
frame = mel_frame[i]
audio = vocoder_inference(
cfg,
model,
mel.unsqueeze(0),
f0s=f0.unsqueeze(0),
device=device,
fast_inference=fast_inference,
).squeeze(0)
# calculate the audio length
audio_length = frame * cfg.preprocess.hop_size
audio = audio[:audio_length]
audios.append(audio)
return audios | Inference the vocoder Args: mels: A list of mel-specs Returns: audios: A list of audios |
17,652 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt
def Conv1d(*args, **kwargs):
layer = nn.Conv1d(*args, **kwargs)
nn.init.kaiming_normal_(layer.weight)
return layer | null |
17,653 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt
def silu(x):
return x * torch.sigmoid(x) | null |
17,654 | import torch
from torch.autograd import Variable
import torch.nn.functional as F
def 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 | null |
17,655 | import torch
from torch.autograd import Variable
import torch.nn.functional as F
def remove(conv_list):
new_conv_list = torch.nn.ModuleList()
for old_conv in conv_list:
old_conv = torch.nn.utils.remove_weight_norm(old_conv)
new_conv_list.append(old_conv)
return new_conv_list | null |
17,656 | import torch
from torch.nn.utils.rnn import pad_sequence
from utils.data_utils import *
from models.tts.base.tts_dataset import (
TTSDataset,
TTSCollator,
TTSTestDataset,
TTSTestCollator,
)
from torch.utils.data.sampler import (
BatchSampler,
RandomSampler,
SequentialSampler,
)
from utils.tokenizer import tokenize_audio
def _is_batch_full(batch, num_tokens, max_tokens, max_sentences):
if len(batch) == 0:
return 0
if len(batch) == max_sentences:
return 1
if num_tokens > max_tokens:
return 1
return 0
The provided code snippet includes necessary dependencies for implementing the `batch_by_size` function. Write a Python function `def batch_by_size( indices, num_tokens_fn, max_tokens=None, max_sentences=None, required_batch_size_multiple=1, )` to solve the following problem:
Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index max_tokens (int, optional): max number of tokens in each batch (default: None). max_sentences (int, optional): max number of sentences in each batch (default: None). required_batch_size_multiple (int, optional): require batch size to be a multiple of N (default: 1).
Here is the function:
def batch_by_size(
indices,
num_tokens_fn,
max_tokens=None,
max_sentences=None,
required_batch_size_multiple=1,
):
"""
Yield mini-batches of indices bucketed by size. Batches may contain
sequences of different lengths.
Args:
indices (List[int]): ordered list of dataset indices
num_tokens_fn (callable): function that returns the number of tokens at
a given index
max_tokens (int, optional): max number of tokens in each batch
(default: None).
max_sentences (int, optional): max number of sentences in each
batch (default: None).
required_batch_size_multiple (int, optional): require batch size to
be a multiple of N (default: 1).
"""
bsz_mult = required_batch_size_multiple
sample_len = 0
sample_lens = []
batch = []
batches = []
for i in range(len(indices)):
idx = indices[i]
num_tokens = num_tokens_fn(idx)
sample_lens.append(num_tokens)
sample_len = max(sample_len, num_tokens)
assert (
sample_len <= max_tokens
), "sentence at index {} of size {} exceeds max_tokens " "limit of {}!".format(
idx, sample_len, max_tokens
)
num_tokens = (len(batch) + 1) * sample_len
if _is_batch_full(batch, num_tokens, max_tokens, max_sentences):
mod_len = max(
bsz_mult * (len(batch) // bsz_mult),
len(batch) % bsz_mult,
)
batches.append(batch[:mod_len])
batch = batch[mod_len:]
sample_lens = sample_lens[mod_len:]
sample_len = max(sample_lens) if len(sample_lens) > 0 else 0
batch.append(idx)
if len(batch) > 0:
batches.append(batch)
return batches | Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index max_tokens (int, optional): max number of tokens in each batch (default: None). max_sentences (int, optional): max number of sentences in each batch (default: None). required_batch_size_multiple (int, optional): require batch size to be a multiple of N (default: 1). |
17,657 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from modules.transformer.Models import Encoder, Decoder
from modules.transformer.Layers import PostNet
from collections import OrderedDict
import os
import json
def get_mask_from_lengths(lengths, max_len=None):
device = lengths.device
batch_size = lengths.shape[0]
if max_len is None:
max_len = torch.max(lengths).item()
ids = torch.arange(0, max_len).unsqueeze(0).expand(batch_size, -1).to(device)
mask = ids >= lengths.unsqueeze(1).expand(-1, max_len)
return mask | null |
17,658 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from modules.transformer.Models import Encoder, Decoder
from modules.transformer.Layers import PostNet
from collections import OrderedDict
import os
import json
def pad(input_ele, mel_max_length=None):
if mel_max_length:
max_len = mel_max_length
else:
max_len = max([input_ele[i].size(0) for i in range(len(input_ele))])
out_list = list()
for i, batch in enumerate(input_ele):
if len(batch.shape) == 1:
one_batch_padded = F.pad(
batch, (0, max_len - batch.size(0)), "constant", 0.0
)
elif len(batch.shape) == 2:
one_batch_padded = F.pad(
batch, (0, 0, 0, max_len - batch.size(0)), "constant", 0.0
)
out_list.append(one_batch_padded)
out_padded = torch.stack(out_list)
return out_padded | null |
17,659 | import random
import torch
from torch.nn.utils.rnn import pad_sequence
from utils.data_utils import *
from processors.acoustic_extractor import cal_normalized_mel
from processors.acoustic_extractor import load_normalized
from models.base.base_dataset import (
BaseOfflineCollator,
BaseOfflineDataset,
BaseTestDataset,
BaseTestCollator,
)
from text import text_to_sequence
from text.cmudict import valid_symbols
from tqdm import tqdm
import pickle
def _is_batch_full(batch, num_tokens, max_tokens, max_sentences):
if len(batch) == 0:
return 0
if len(batch) == max_sentences:
return 1
if num_tokens > max_tokens:
return 1
return 0
The provided code snippet includes necessary dependencies for implementing the `batch_by_size` function. Write a Python function `def batch_by_size( indices, num_tokens_fn, max_tokens=None, max_sentences=None, required_batch_size_multiple=1, )` to solve the following problem:
Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index max_tokens (int, optional): max number of tokens in each batch (default: None). max_sentences (int, optional): max number of sentences in each batch (default: None). required_batch_size_multiple (int, optional): require batch size to be a multiple of N (default: 1).
Here is the function:
def batch_by_size(
indices,
num_tokens_fn,
max_tokens=None,
max_sentences=None,
required_batch_size_multiple=1,
):
"""
Yield mini-batches of indices bucketed by size. Batches may contain
sequences of different lengths.
Args:
indices (List[int]): ordered list of dataset indices
num_tokens_fn (callable): function that returns the number of tokens at
a given index
max_tokens (int, optional): max number of tokens in each batch
(default: None).
max_sentences (int, optional): max number of sentences in each
batch (default: None).
required_batch_size_multiple (int, optional): require batch size to
be a multiple of N (default: 1).
"""
bsz_mult = required_batch_size_multiple
sample_len = 0
sample_lens = []
batch = []
batches = []
for i in range(len(indices)):
idx = indices[i]
num_tokens = num_tokens_fn(idx)
sample_lens.append(num_tokens)
sample_len = max(sample_len, num_tokens)
assert (
sample_len <= max_tokens
), "sentence at index {} of size {} exceeds max_tokens " "limit of {}!".format(
idx, sample_len, max_tokens
)
num_tokens = (len(batch) + 1) * sample_len
if _is_batch_full(batch, num_tokens, max_tokens, max_sentences):
mod_len = max(
bsz_mult * (len(batch) // bsz_mult),
len(batch) % bsz_mult,
)
batches.append(batch[:mod_len])
batch = batch[mod_len:]
sample_lens = sample_lens[mod_len:]
sample_len = max(sample_lens) if len(sample_lens) > 0 else 0
batch.append(idx)
if len(batch) > 0:
batches.append(batch)
return batches | Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index max_tokens (int, optional): max number of tokens in each batch (default: None). max_sentences (int, optional): max number of sentences in each batch (default: None). required_batch_size_multiple (int, optional): require batch size to be a multiple of N (default: 1). |
17,660 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
import math
def Conv1d(*args, **kwargs):
layer = nn.Conv1d(*args, **kwargs)
nn.init.kaiming_normal_(layer.weight)
return layer | null |
17,661 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
import math
def Linear(*args, **kwargs):
layer = nn.Linear(*args, **kwargs)
layer.weight.data.normal_(0.0, 0.02)
return layer | null |
17,662 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
def log_dur_loss(dur_pred_log, dur_target, mask, loss_type="l1"):
# dur_pred_log: (B, N)
# dur_target: (B, N)
# mask: (B, N) mask is 0
dur_target_log = torch.log(1 + dur_target)
if loss_type == "l1":
loss = F.l1_loss(
dur_pred_log, dur_target_log, reduction="none"
).float() * mask.to(dur_target.dtype)
elif loss_type == "l2":
loss = F.mse_loss(
dur_pred_log, dur_target_log, reduction="none"
).float() * mask.to(dur_target.dtype)
else:
raise NotImplementedError()
loss = loss.sum() / (mask.to(dur_target.dtype).sum())
return loss | null |
17,663 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
def log_pitch_loss(pitch_pred_log, pitch_target, mask, loss_type="l1"):
pitch_target_log = torch.log(pitch_target)
if loss_type == "l1":
loss = F.l1_loss(
pitch_pred_log, pitch_target_log, reduction="none"
).float() * mask.to(pitch_target.dtype)
elif loss_type == "l2":
loss = F.mse_loss(
pitch_pred_log, pitch_target_log, reduction="none"
).float() * mask.to(pitch_target.dtype)
else:
raise NotImplementedError()
loss = loss.sum() / (mask.to(pitch_target.dtype).sum() + 1e-8)
return loss | null |
17,664 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
def diff_loss(pred, target, mask, loss_type="l1"):
# pred: (B, d, T)
# target: (B, d, T)
# mask: (B, T)
if loss_type == "l1":
loss = F.l1_loss(pred, target, reduction="none").float() * (
mask.to(pred.dtype).unsqueeze(1)
)
elif loss_type == "l2":
loss = F.mse_loss(pred, target, reduction="none").float() * (
mask.to(pred.dtype).unsqueeze(1)
)
else:
raise NotImplementedError()
loss = (torch.mean(loss, dim=1)).sum() / (mask.to(pred.dtype).sum())
return loss | null |
17,665 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
def diff_ce_loss(pred_dist, gt_indices, mask):
# pred_dist: (nq, B, T, 1024)
# gt_indices: (nq, B, T)
pred_dist = pred_dist.permute(1, 3, 0, 2) # (B, 1024, nq, T)
gt_indices = gt_indices.permute(1, 0, 2).long() # (B, nq, T)
loss = F.cross_entropy(
pred_dist, gt_indices, reduction="none"
).float() # (B, nq, T)
loss = loss * mask.to(loss.dtype).unsqueeze(1)
loss = (torch.mean(loss, dim=1)).sum() / (mask.to(loss.dtype).sum())
return loss | null |
17,666 | import numpy as np
import torch
from torch import nn, sin, pow
from torch.nn import Parameter
import torch.nn.functional as F
from torch.nn.utils import weight_norm
from .alias_free_torch import *
from .quantize import *
from einops import rearrange
from einops.layers.torch import Rearrange
from .transformer import TransformerEncoder
from .gradient_reversal import GradientReversal
def init_weights(m):
if isinstance(m, nn.Conv1d):
nn.init.trunc_normal_(m.weight, std=0.02)
nn.init.constant_(m.bias, 0) | null |
17,667 | import numpy as np
import torch
from torch import nn, sin, pow
from torch.nn import Parameter
import torch.nn.functional as F
from torch.nn.utils import weight_norm
from .alias_free_torch import *
from .quantize import *
from einops import rearrange
from einops.layers.torch import Rearrange
from .transformer import TransformerEncoder
from .gradient_reversal import GradientReversal
def WNConv1d(*args, **kwargs):
return weight_norm(nn.Conv1d(*args, **kwargs)) | null |
17,668 | import numpy as np
import torch
from torch import nn, sin, pow
from torch.nn import Parameter
import torch.nn.functional as F
from torch.nn.utils import weight_norm
from .alias_free_torch import *
from .quantize import *
from einops import rearrange
from einops.layers.torch import Rearrange
from .transformer import TransformerEncoder
from .gradient_reversal import GradientReversal
def WNConvTranspose1d(*args, **kwargs):
return weight_norm(nn.ConvTranspose1d(*args, **kwargs)) | null |
17,670 | import math
import random
from torch.utils.data import ConcatDataset, Dataset
from torch.utils.data.sampler import (
BatchSampler,
RandomSampler,
Sampler,
SequentialSampler,
)
class ScheduledSampler(Sampler):
"""A sampler that samples data from a given concat-dataset.
Args:
concat_dataset (ConcatDataset): a concatenated dataset consisting of all datasets
batch_size (int): batch size
holistic_shuffle (bool): whether to shuffle the whole dataset or not
logger (logging.Logger): logger to print warning message
Usage:
For cfg.train.batch_size = 3, cfg.train.holistic_shuffle = False, cfg.train.drop_last = True:
>>> list(ScheduledSampler(ConcatDataset([[0, 1, 2], [3, 4, 5], [6, 7, 8]])))
[3, 4, 5, 0, 1, 2, 6, 7, 8]
"""
def __init__(
self,
concat_dataset,
batch_size,
holistic_shuffle,
logger=None,
loader_type="train",
):
if not isinstance(concat_dataset, ConcatDataset):
raise ValueError(
"concat_dataset must be an instance of ConcatDataset, but got {}".format(
type(concat_dataset)
)
)
if not isinstance(batch_size, int):
raise ValueError(
"batch_size must be an integer, but got {}".format(type(batch_size))
)
if not isinstance(holistic_shuffle, bool):
raise ValueError(
"holistic_shuffle must be a boolean, but got {}".format(
type(holistic_shuffle)
)
)
self.concat_dataset = concat_dataset
self.batch_size = batch_size
self.holistic_shuffle = holistic_shuffle
affected_dataset_name = []
affected_dataset_len = []
for dataset in concat_dataset.datasets:
dataset_len = len(dataset)
dataset_name = dataset.get_dataset_name()
if dataset_len < batch_size:
affected_dataset_name.append(dataset_name)
affected_dataset_len.append(dataset_len)
self.type = loader_type
for dataset_name, dataset_len in zip(
affected_dataset_name, affected_dataset_len
):
if not loader_type == "valid":
logger.warning(
"The {} dataset {} has a length of {}, which is smaller than the batch size {}. This may cause unexpected behavior.".format(
loader_type, dataset_name, dataset_len, batch_size
)
)
def __len__(self):
# the number of batches with drop last
num_of_batches = sum(
[
math.floor(len(dataset) / self.batch_size)
for dataset in self.concat_dataset.datasets
]
)
# if samples are not enough for one batch, we don't drop last
if self.type == "valid" and num_of_batches < 1:
return len(self.concat_dataset)
return num_of_batches * self.batch_size
def __iter__(self):
iters = []
for dataset in self.concat_dataset.datasets:
iters.append(
SequentialSampler(dataset).__iter__()
if not self.holistic_shuffle
else RandomSampler(dataset).__iter__()
)
# e.g. [0, 200, 400]
init_indices = [0] + self.concat_dataset.cumulative_sizes[:-1]
output_batches = []
for dataset_idx in range(len(self.concat_dataset.datasets)):
cur_batch = []
for idx in iters[dataset_idx]:
cur_batch.append(idx + init_indices[dataset_idx])
if len(cur_batch) == self.batch_size:
output_batches.append(cur_batch)
cur_batch = []
# if loader_type is valid, we don't need to drop last
if self.type == "valid" and len(cur_batch) > 0:
output_batches.append(cur_batch)
# force drop last in training
random.shuffle(output_batches)
output_indices = [item for sublist in output_batches for item in sublist]
return iter(output_indices)
def build_samplers(concat_dataset: Dataset, cfg, logger, loader_type):
sampler = ScheduledSampler(
concat_dataset,
cfg.train.batch_size,
cfg.train.sampler.holistic_shuffle,
logger,
loader_type,
)
batch_sampler = BatchSampler(
sampler,
cfg.train.batch_size,
cfg.train.sampler.drop_last if not loader_type == "valid" else False,
)
return sampler, batch_sampler | null |
17,671 | import argparse
import os
import re
import time
from pathlib import Path
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from models.vocoders.vocoder_inference import synthesis
from torch.utils.data import DataLoader
from utils.util import set_all_random_seed
from utils.util import load_config
def load_config(config_fn, lowercase=False):
"""Load configurations into a dictionary
Args:
config_fn (str): path to configuration file
lowercase (bool, optional): _description_. Defaults to False.
Returns:
JsonHParams: an object that stores configurations
"""
config_ = _load_config(config_fn, lowercase=lowercase)
# create an JsonHParams object with configuration dict
cfg = JsonHParams(**config_)
return cfg
The provided code snippet includes necessary dependencies for implementing the `parse_vocoder` function. Write a Python function `def parse_vocoder(vocoder_dir)` to solve the following problem:
r"""Parse vocoder config
Here is the function:
def parse_vocoder(vocoder_dir):
r"""Parse vocoder config"""
vocoder_dir = os.path.abspath(vocoder_dir)
ckpt_list = [ckpt for ckpt in Path(vocoder_dir).glob("*.pt")]
ckpt_list.sort(key=lambda x: int(x.stem), reverse=True)
ckpt_path = str(ckpt_list[0])
vocoder_cfg = load_config(os.path.join(vocoder_dir, "args.json"), lowercase=True)
vocoder_cfg.model.bigvgan = vocoder_cfg.vocoder
return vocoder_cfg, ckpt_path | r"""Parse vocoder config |
17,672 | import argparse
import os
import re
import time
from pathlib import Path
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from models.vocoders.vocoder_inference import synthesis
from torch.utils.data import DataLoader
from utils.util import set_all_random_seed
from utils.util import load_config
def base_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
"--config", default="config.json", help="json files for configurations."
)
parser.add_argument("--use_ddp_inference", default=False)
parser.add_argument("--n_workers", default=1, type=int)
parser.add_argument("--local_rank", default=-1, type=int)
parser.add_argument(
"--batch_size", default=1, type=int, help="Batch size for inference"
)
parser.add_argument(
"--num_workers",
default=1,
type=int,
help="Worker number for inference dataloader",
)
parser.add_argument(
"--checkpoint_dir",
type=str,
default=None,
help="Checkpoint dir including model file and configuration",
)
parser.add_argument(
"--checkpoint_file", help="checkpoint file", type=str, default=None
)
parser.add_argument(
"--test_list", help="test utterance list for testing", type=str, default=None
)
parser.add_argument(
"--checkpoint_dir_vocoder",
help="Vocoder's checkpoint dir including model file and configuration",
type=str,
default=None,
)
parser.add_argument(
"--output_dir",
type=str,
default=None,
help="Output dir for saving generated results",
)
return parser | null |
17,673 | import re
from typing import Any, Dict, List, Optional, Pattern, Union
import torch
import torchaudio
from encodec import EncodecModel
from encodec.utils import convert_audio
class AudioTokenizer:
"""EnCodec audio tokenizer for encoding and decoding audio.
Attributes:
device: The device on which the codec model is loaded.
codec: The pretrained EnCodec model.
sample_rate: Sample rate of the model.
channels: Number of audio channels in the model.
"""
def __init__(self, device: Any = None) -> None:
model = EncodecModel.encodec_model_24khz()
model.set_target_bandwidth(6.0)
remove_encodec_weight_norm(model)
if not device:
device = torch.device("cpu")
if torch.cuda.is_available():
device = torch.device("cuda:0")
self._device = device
self.codec = model.to(device)
self.sample_rate = model.sample_rate
self.channels = model.channels
def device(self):
return self._device
def encode(self, wav: torch.Tensor) -> torch.Tensor:
"""Encode the audio waveform.
Args:
wav: A tensor representing the audio waveform.
Returns:
A tensor representing the encoded audio.
"""
return self.codec.encode(wav.to(self.device))
def decode(self, frames: torch.Tensor) -> torch.Tensor:
"""Decode the encoded audio frames.
Args:
frames: A tensor representing the encoded audio frames.
Returns:
A tensor representing the decoded audio waveform.
"""
return self.codec.decode(frames)
The provided code snippet includes necessary dependencies for implementing the `tokenize_audio` function. Write a Python function `def tokenize_audio(tokenizer: AudioTokenizer, audio_path: str)` to solve the following problem:
Tokenize the audio waveform using the given AudioTokenizer. Args: tokenizer: An instance of AudioTokenizer. audio_path: Path to the audio file. Returns: A tensor of encoded frames from the audio. Raises: FileNotFoundError: If the audio file is not found. RuntimeError: If there's an error processing the audio data.
Here is the function:
def tokenize_audio(tokenizer: AudioTokenizer, audio_path: str):
"""
Tokenize the audio waveform using the given AudioTokenizer.
Args:
tokenizer: An instance of AudioTokenizer.
audio_path: Path to the audio file.
Returns:
A tensor of encoded frames from the audio.
Raises:
FileNotFoundError: If the audio file is not found.
RuntimeError: If there's an error processing the audio data.
"""
# try:
# Load and preprocess the audio waveform
wav, sr = torchaudio.load(audio_path)
wav = convert_audio(wav, sr, tokenizer.sample_rate, tokenizer.channels)
wav = wav.unsqueeze(0)
# Extract discrete codes from EnCodec
with torch.no_grad():
encoded_frames = tokenizer.encode(wav)
return encoded_frames
# except FileNotFoundError:
# raise FileNotFoundError(f"Audio file not found at {audio_path}")
# except Exception as e:
# raise RuntimeError(f"Error processing audio data: {e}") | Tokenize the audio waveform using the given AudioTokenizer. Args: tokenizer: An instance of AudioTokenizer. audio_path: Path to the audio file. Returns: A tensor of encoded frames from the audio. Raises: FileNotFoundError: If the audio file is not found. RuntimeError: If there's an error processing the audio data. |
17,674 | import re
from typing import Any, Dict, List, Optional, Pattern, Union
import torch
import torchaudio
from encodec import EncodecModel
from encodec.utils import convert_audio
def remove_encodec_weight_norm(model):
from encodec.modules import SConv1d
from encodec.modules.seanet import SConvTranspose1d, SEANetResnetBlock
from torch.nn.utils import remove_weight_norm
encoder = model.encoder.model
for key in encoder._modules:
if isinstance(encoder._modules[key], SEANetResnetBlock):
remove_weight_norm(encoder._modules[key].shortcut.conv.conv)
block_modules = encoder._modules[key].block._modules
for skey in block_modules:
if isinstance(block_modules[skey], SConv1d):
remove_weight_norm(block_modules[skey].conv.conv)
elif isinstance(encoder._modules[key], SConv1d):
remove_weight_norm(encoder._modules[key].conv.conv)
decoder = model.decoder.model
for key in decoder._modules:
if isinstance(decoder._modules[key], SEANetResnetBlock):
remove_weight_norm(decoder._modules[key].shortcut.conv.conv)
block_modules = decoder._modules[key].block._modules
for skey in block_modules:
if isinstance(block_modules[skey], SConv1d):
remove_weight_norm(block_modules[skey].conv.conv)
elif isinstance(decoder._modules[key], SConvTranspose1d):
remove_weight_norm(decoder._modules[key].convtr.convtr)
elif isinstance(decoder._modules[key], SConv1d):
remove_weight_norm(decoder._modules[key].conv.conv) | null |
17,675 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
The provided code snippet includes necessary dependencies for implementing the `str2bool` function. Write a Python function `def str2bool(v)` to solve the following problem:
Used in argparse.ArgumentParser.add_argument to indicate that a type is a bool type and user can enter - yes, true, t, y, 1, to represent True - no, false, f, n, 0, to represent False See https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse # noqa
Here is the function:
def str2bool(v):
"""Used in argparse.ArgumentParser.add_argument to indicate
that a type is a bool type and user can enter
- yes, true, t, y, 1, to represent True
- no, false, f, n, 0, to represent False
See https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse # noqa
"""
if isinstance(v, bool):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise argparse.ArgumentTypeError("Boolean value expected.") | Used in argparse.ArgumentParser.add_argument to indicate that a type is a bool type and user can enter - yes, true, t, y, 1, to represent True - no, false, f, n, 0, to represent False See https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse # noqa |
17,676 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def find_checkpoint_of_mapper(mapper_ckpt_dir):
mapper_ckpts = glob.glob(os.path.join(mapper_ckpt_dir, "ckpts/*.pt"))
# Select the max steps
mapper_ckpts.sort()
mapper_weights_file = mapper_ckpts[-1]
return mapper_weights_file | null |
17,677 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def load_config(config_fn, lowercase=False):
"""Load configurations into a dictionary
Args:
config_fn (str): path to configuration file
lowercase (bool, optional): _description_. Defaults to False.
Returns:
JsonHParams: an object that stores configurations
"""
config_ = _load_config(config_fn, lowercase=lowercase)
# create an JsonHParams object with configuration dict
cfg = JsonHParams(**config_)
return cfg
The provided code snippet includes necessary dependencies for implementing the `load_model_config` function. Write a Python function `def load_model_config(args)` to solve the following problem:
Load model configurations (in args.json under checkpoint directory) Args: args (ArgumentParser): arguments to run bins/preprocess.py Returns: dict: dictionary that stores model configurations
Here is the function:
def load_model_config(args):
"""Load model configurations (in args.json under checkpoint directory)
Args:
args (ArgumentParser): arguments to run bins/preprocess.py
Returns:
dict: dictionary that stores model configurations
"""
if args.checkpoint_dir is None:
assert args.checkpoint_file is not None
checkpoint_dir = os.path.split(args.checkpoint_file)[0]
else:
checkpoint_dir = args.checkpoint_dir
config_path = os.path.join(checkpoint_dir, "args.json")
print("config_path: ", config_path)
config = load_config(config_path)
return config | Load model configurations (in args.json under checkpoint directory) Args: args (ArgumentParser): arguments to run bins/preprocess.py Returns: dict: dictionary that stores model configurations |
17,678 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def remove_older_ckpt(saved_model_name, checkpoint_dir, max_to_keep=5):
if os.path.exists(os.path.join(checkpoint_dir, "checkpoint")):
with open(os.path.join(checkpoint_dir, "checkpoint"), "r") as f:
ckpts = [x.strip() for x in f.readlines()]
else:
ckpts = []
ckpts.append(saved_model_name)
for item in ckpts[:-max_to_keep]:
if os.path.exists(os.path.join(checkpoint_dir, item)):
os.remove(os.path.join(checkpoint_dir, item))
with open(os.path.join(checkpoint_dir, "checkpoint"), "w") as f:
for item in ckpts[-max_to_keep:]:
f.write("{}\n".format(item)) | null |
17,679 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def set_all_random_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed) | null |
17,680 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def save_checkpoint(
args,
generator,
g_optimizer,
step,
discriminator=None,
d_optimizer=None,
max_to_keep=5,
):
saved_model_name = "model.ckpt-{}.pt".format(step)
checkpoint_path = os.path.join(args.checkpoint_dir, saved_model_name)
if discriminator and d_optimizer:
torch.save(
{
"generator": generator.state_dict(),
"discriminator": discriminator.state_dict(),
"g_optimizer": g_optimizer.state_dict(),
"d_optimizer": d_optimizer.state_dict(),
"global_step": step,
},
checkpoint_path,
)
else:
torch.save(
{
"generator": generator.state_dict(),
"g_optimizer": g_optimizer.state_dict(),
"global_step": step,
},
checkpoint_path,
)
print("Saved checkpoint: {}".format(checkpoint_path))
if os.path.exists(os.path.join(args.checkpoint_dir, "checkpoint")):
with open(os.path.join(args.checkpoint_dir, "checkpoint"), "r") as f:
ckpts = [x.strip() for x in f.readlines()]
else:
ckpts = []
ckpts.append(saved_model_name)
for item in ckpts[:-max_to_keep]:
if os.path.exists(os.path.join(args.checkpoint_dir, item)):
os.remove(os.path.join(args.checkpoint_dir, item))
with open(os.path.join(args.checkpoint_dir, "checkpoint"), "w") as f:
for item in ckpts[-max_to_keep:]:
f.write("{}\n".format(item)) | null |
17,681 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def attempt_to_restore(
generator, g_optimizer, checkpoint_dir, discriminator=None, d_optimizer=None
):
checkpoint_list = os.path.join(checkpoint_dir, "checkpoint")
if os.path.exists(checkpoint_list):
checkpoint_filename = open(checkpoint_list).readlines()[-1].strip()
checkpoint_path = os.path.join(checkpoint_dir, "{}".format(checkpoint_filename))
print("Restore from {}".format(checkpoint_path))
checkpoint = torch.load(checkpoint_path, map_location="cpu")
if generator:
if not list(generator.state_dict().keys())[0].startswith("module."):
raw_dict = checkpoint["generator"]
clean_dict = OrderedDict()
for k, v in raw_dict.items():
if k.startswith("module."):
clean_dict[k[7:]] = v
else:
clean_dict[k] = v
generator.load_state_dict(clean_dict)
else:
generator.load_state_dict(checkpoint["generator"])
if g_optimizer:
g_optimizer.load_state_dict(checkpoint["g_optimizer"])
global_step = 100000
if discriminator and "discriminator" in checkpoint.keys():
discriminator.load_state_dict(checkpoint["discriminator"])
global_step = checkpoint["global_step"]
print("restore discriminator")
if d_optimizer and "d_optimizer" in checkpoint.keys():
d_optimizer.load_state_dict(checkpoint["d_optimizer"])
print("restore d_optimizer...")
else:
global_step = 0
return global_step | null |
17,682 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def apply_moving_average(model, ema):
for name, param in model.named_parameters():
if name in ema.shadow:
ema.update(name, param.data) | null |
17,683 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def register_model_to_ema(model, ema):
for name, param in model.named_parameters():
if param.requires_grad:
ema.register(name, param.data) | null |
17,684 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
The provided code snippet includes necessary dependencies for implementing the `save_config` function. Write a Python function `def save_config(save_path, cfg)` to solve the following problem:
Save configurations into a json file Args: save_path (str): path to save configurations cfg (dict): dictionary that stores configurations
Here is the function:
def save_config(save_path, cfg):
"""Save configurations into a json file
Args:
save_path (str): path to save configurations
cfg (dict): dictionary that stores configurations
"""
with open(save_path, "w") as f:
json5.dump(
cfg, f, ensure_ascii=False, indent=4, quote_keys=True, sort_keys=True
) | Save configurations into a json file Args: save_path (str): path to save configurations cfg (dict): dictionary that stores configurations |
17,685 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
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) | null |
17,686 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def get_padding(kernel_size, dilation=1):
return int((kernel_size * dilation - dilation) / 2) | null |
17,687 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
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 | null |
17,688 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def subsequent_mask(length):
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
return mask | null |
17,689 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def 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 | null |
17,690 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
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 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)
The provided code snippet includes necessary dependencies for implementing the `generate_path` function. Write a Python function `def generate_path(duration, mask)` to solve the following problem:
duration: [b, 1, t_x] mask: [b, 1, t_y, t_x]
Here is the function:
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 | duration: [b, 1, t_x] mask: [b, 1, t_y, t_x] |
17,691 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
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.0 / norm_type)
return total_norm | null |
17,692 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
def get_current_time():
pass | null |
17,693 | import collections
import glob
import os
import random
import time
import argparse
from collections import OrderedDict
import json5
import numpy as np
import glob
from torch.nn import functional as F
import torch
from utils.hparam import HParams
import logging
from logging import handlers
The provided code snippet includes necessary dependencies for implementing the `make_pad_mask` function. Write a Python function `def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor` to solve the following problem:
Args: lengths: A 1-D tensor containing sentence lengths. max_len: The length of masks. Returns: Return a 2-D bool tensor, where masked positions are filled with `True` and non-masked positions are filled with `False`. >>> lengths = torch.tensor([1, 3, 2, 5]) >>> make_pad_mask(lengths) tensor([[False, True, True, True, True], [False, False, False, True, True], [False, False, True, True, True], [False, False, False, False, False]])
Here is the function:
def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
"""
Args:
lengths:
A 1-D tensor containing sentence lengths.
max_len:
The length of masks.
Returns:
Return a 2-D bool tensor, where masked positions
are filled with `True` and non-masked positions are
filled with `False`.
>>> lengths = torch.tensor([1, 3, 2, 5])
>>> make_pad_mask(lengths)
tensor([[False, True, True, True, True],
[False, False, False, True, True],
[False, False, True, True, True],
[False, False, False, False, False]])
"""
assert lengths.ndim == 1, lengths.ndim
max_len = max(max_len, lengths.max())
n = lengths.size(0)
seq_range = torch.arange(0, max_len, device=lengths.device)
expaned_lengths = seq_range.unsqueeze(0).expand(n, max_len)
return expaned_lengths >= lengths.unsqueeze(-1) | Args: lengths: A 1-D tensor containing sentence lengths. max_len: The length of masks. Returns: Return a 2-D bool tensor, where masked positions are filled with `True` and non-masked positions are filled with `False`. >>> lengths = torch.tensor([1, 3, 2, 5]) >>> make_pad_mask(lengths) tensor([[False, True, True, True, True], [False, False, False, True, True], [False, False, True, True, True], [False, False, False, False, False]]) |
17,694 | import torch
import torch.nn.functional as F
def top_k_top_p_filtering(
logits, top_k=0, top_p=1.0, filter_value=-float("Inf"), min_tokens_to_keep=1
):
"""
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering.
Args:
logits (torch.Tensor): Logits distribution with shape (batch size, vocabulary size).
top_k (int, optional): Keep only top k tokens with highest probability (top-k filtering).
Set to 0 to disable. Defaults to 0.
top_p (float, optional): Keep the top tokens with a cumulative probability >= top_p (nucleus filtering).
Must be between 0 and 1, inclusive. Defaults to 1.0.
filter_value (float, optional): The value to assign to filtered logits. Defaults to -float('Inf').
min_tokens_to_keep (int, optional): Ensure that at least this number of tokens are kept per batch example.
Defaults to 1.
Returns:
torch.Tensor: The filtered logits.
"""
"""
Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
Make sure we keep at least min_tokens_to_keep per batch example in the output
From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
"""
if top_k > 0:
# Apply top-k filtering
top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1))
indices_to_remove = logits < torch.topk(logits, top_k).values[..., -1, None]
logits[indices_to_remove] = filter_value
if top_p < 1.0:
# Apply top-p filtering
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# Create a mask to remove tokens with cumulative probability above the top_p threshold
sorted_indices_to_remove = cumulative_probs > top_p
if min_tokens_to_keep > 1:
sorted_indices_to_remove[..., :min_tokens_to_keep] = 0
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
# Scatter sorted tensors back to original indexing
indices_to_remove = sorted_indices.scatter(
1, sorted_indices, sorted_indices_to_remove
)
logits[indices_to_remove] = filter_value
return logits
The provided code snippet includes necessary dependencies for implementing the `topk_sampling` function. Write a Python function `def topk_sampling(logits, top_k=50, top_p=1.0, temperature=1.0)` to solve the following problem:
Perform top-k and top-p sampling on logits. Args: logits (torch.Tensor): The logits to sample from. top_k (int, optional): The number of highest probability tokens to keep for top-k filtering. Must be a positive integer. Defaults to 50. top_p (float, optional): The cumulative probability threshold for nucleus sampling. Must be between 0 and 1. Defaults to 1.0. temperature (float, optional): The scaling factor to adjust the logits distribution. Must be strictly positive. Defaults to 1.0. Returns: torch.Tensor: The sampled token.
Here is the function:
def topk_sampling(logits, top_k=50, top_p=1.0, temperature=1.0):
"""
Perform top-k and top-p sampling on logits.
Args:
logits (torch.Tensor): The logits to sample from.
top_k (int, optional): The number of highest probability tokens to keep for top-k filtering.
Must be a positive integer. Defaults to 50.
top_p (float, optional): The cumulative probability threshold for nucleus sampling.
Must be between 0 and 1. Defaults to 1.0.
temperature (float, optional): The scaling factor to adjust the logits distribution.
Must be strictly positive. Defaults to 1.0.
Returns:
torch.Tensor: The sampled token.
"""
# Adjust logits using temperature
if temperature != 1.0:
logits = logits / temperature
# Top-p/top-k filtering
logits = top_k_top_p_filtering(logits, top_k=top_k, top_p=top_p)
# Sample from the filtered distribution
token = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
return token | Perform top-k and top-p sampling on logits. Args: logits (torch.Tensor): The logits to sample from. top_k (int, optional): The number of highest probability tokens to keep for top-k filtering. Must be a positive integer. Defaults to 50. top_p (float, optional): The cumulative probability threshold for nucleus sampling. Must be between 0 and 1. Defaults to 1.0. temperature (float, optional): The scaling factor to adjust the logits distribution. Must be strictly positive. Defaults to 1.0. Returns: torch.Tensor: The sampled token. |
17,695 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
The provided code snippet includes necessary dependencies for implementing the `intersperse` function. Write a Python function `def intersperse(lst, item)` to solve the following problem:
Insert an item in between any two consecutive elements of the given list, including beginning and end of list Example: >>> intersperse(0, [1, 74, 5, 31]) [0, 1, 0, 74, 0, 5, 0, 31, 0]
Here is the function:
def intersperse(lst, item):
"""
Insert an item in between any two consecutive elements of the given list, including beginning and end of list
Example:
>>> intersperse(0, [1, 74, 5, 31])
[0, 1, 0, 74, 0, 5, 0, 31, 0]
"""
result = [item] * (len(lst) * 2 + 1)
result[1::2] = lst
return result | Insert an item in between any two consecutive elements of the given list, including beginning and end of list Example: >>> intersperse(0, [1, 74, 5, 31]) [0, 1, 0, 74, 0, 5, 0, 31, 0] |
17,696 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def load_content_feature_path(meta_data, processed_dir, feat_dir):
utt2feat_path = {}
for utt_info in meta_data:
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
feat_path = os.path.join(
processed_dir, utt_info["Dataset"], feat_dir, f'{utt_info["Uid"]}.npy'
)
utt2feat_path[utt] = feat_path
return utt2feat_path | null |
17,697 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def load_source_content_feature_path(meta_data, feat_dir):
utt2feat_path = {}
for utt in meta_data:
feat_path = os.path.join(feat_dir, f"{utt}.npy")
utt2feat_path[utt] = feat_path
return utt2feat_path | null |
17,698 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def get_spk_map(spk2id_path, utt2spk_path):
utt2spk = {}
with open(spk2id_path, "r") as spk2id_file:
spk2id = json.load(spk2id_file)
with open(utt2spk_path, encoding="utf-8") as f:
for line in f.readlines():
utt, spk = line.strip().split("\t")
utt2spk[utt] = spk
return spk2id, utt2spk | null |
17,699 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def get_target_f0_median(f0_dir):
total_f0 = []
for utt in os.listdir(f0_dir):
if not utt.endswith(".npy"):
continue
f0_feat_path = os.path.join(f0_dir, utt)
f0 = np.load(f0_feat_path)
total_f0 += f0.tolist()
total_f0 = np.array(total_f0)
voiced_position = np.where(total_f0 != 0)
return np.median(total_f0[voiced_position]) | null |
17,700 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def transpose_key(frame_pitch, trans_key):
# Transpose by user's argument
print("Transpose key = {} ...\n".format(trans_key))
transed_pitch = frame_pitch * 2 ** (trans_key / 12)
return transed_pitch | null |
17,701 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def get_conversion_f0_factor(source_f0, target_median, source_median=None):
"""Align the median between source f0 and target f0
Note: Here we use multiplication, whose factor is target_median/source_median
Reference: Frequency and pitch interval
http://blog.ccyg.studio/article/be12c2ee-d47c-4098-9782-ca76da3035e4/
"""
if source_median is None:
voiced_position = np.where(source_f0 != 0)
source_median = np.median(source_f0[voiced_position])
factor = target_median / source_median
return source_median, factor
def pitch_shift_to_target(frame_pitch, target_pitch_median, source_pitch_median=None):
# Loading F0 Base (median) and shift
source_pitch_median, factor = get_conversion_f0_factor(
frame_pitch, target_pitch_median, source_pitch_median
)
print(
"Auto transposing: source f0 median = {:.1f}, target f0 median = {:.1f}, factor = {:.2f}".format(
source_pitch_median, target_pitch_median, factor
)
)
transed_pitch = frame_pitch * factor
return transed_pitch | null |
17,702 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def load_frame_pitch(
meta_data,
processed_dir,
pitch_dir,
use_log_scale=False,
return_norm=False,
interoperate=False,
utt2spk=None,
):
utt2pitch = {}
utt2uv = {}
if utt2spk is None:
pitch_scaler = StandardScaler()
for utt_info in meta_data:
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
pitch_path = os.path.join(
processed_dir, utt_info["Dataset"], pitch_dir, f'{utt_info["Uid"]}.npy'
)
pitch = np.load(pitch_path)
assert len(pitch) > 0
uv = pitch != 0
utt2uv[utt] = uv
if use_log_scale:
nonzero_idxes = np.where(pitch != 0)[0]
pitch[nonzero_idxes] = np.log(pitch[nonzero_idxes])
utt2pitch[utt] = pitch
pitch_scaler.partial_fit(pitch.reshape(-1, 1))
mean, std = pitch_scaler.mean_[0], pitch_scaler.scale_[0]
if return_norm:
for utt_info in meta_data:
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
pitch = utt2pitch[utt]
normalized_pitch = (pitch - mean) / std
utt2pitch[utt] = normalized_pitch
pitch_statistic = {"mean": mean, "std": std}
else:
spk2utt = {}
pitch_statistic = []
for utt_info in meta_data:
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
if not utt2spk[utt] in spk2utt:
spk2utt[utt2spk[utt]] = []
spk2utt[utt2spk[utt]].append(utt)
for spk in spk2utt:
pitch_scaler = StandardScaler()
for utt in spk2utt[spk]:
dataset = utt.split("_")[0]
uid = "_".join(utt.split("_")[1:])
pitch_path = os.path.join(
processed_dir, dataset, pitch_dir, f"{uid}.npy"
)
pitch = np.load(pitch_path)
assert len(pitch) > 0
uv = pitch != 0
utt2uv[utt] = uv
if use_log_scale:
nonzero_idxes = np.where(pitch != 0)[0]
pitch[nonzero_idxes] = np.log(pitch[nonzero_idxes])
utt2pitch[utt] = pitch
pitch_scaler.partial_fit(pitch.reshape(-1, 1))
mean, std = pitch_scaler.mean_[0], pitch_scaler.scale_[0]
if return_norm:
for utt in spk2utt[spk]:
pitch = utt2pitch[utt]
normalized_pitch = (pitch - mean) / std
utt2pitch[utt] = normalized_pitch
pitch_statistic.append({"spk": spk, "mean": mean, "std": std})
return utt2pitch, utt2uv, pitch_statistic | null |
17,703 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def phone_average_pitch(pitch, dur, interoperate=False):
def remove_outlier(values):
def load_phone_pitch(
meta_data,
processed_dir,
pitch_dir,
utt2dur,
use_log_scale=False,
return_norm=False,
interoperate=True,
utt2spk=None,
):
print("Load Phone Pitch")
utt2pitch = {}
utt2uv = {}
if utt2spk is None:
pitch_scaler = StandardScaler()
for utt_info in tqdm(meta_data):
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
pitch_path = os.path.join(
processed_dir, utt_info["Dataset"], pitch_dir, f'{utt_info["Uid"]}.npy'
)
frame_pitch = np.load(pitch_path)
assert len(frame_pitch) > 0
uv = frame_pitch != 0
utt2uv[utt] = uv
phone_pitch = phone_average_pitch(frame_pitch, utt2dur[utt], interoperate)
if use_log_scale:
nonzero_idxes = np.where(phone_pitch != 0)[0]
phone_pitch[nonzero_idxes] = np.log(phone_pitch[nonzero_idxes])
utt2pitch[utt] = phone_pitch
pitch_scaler.partial_fit(remove_outlier(phone_pitch).reshape(-1, 1))
mean, std = pitch_scaler.mean_[0], pitch_scaler.scale_[0]
max_value = np.finfo(np.float64).min
min_value = np.finfo(np.float64).max
if return_norm:
for utt_info in meta_data:
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
pitch = utt2pitch[utt]
normalized_pitch = (pitch - mean) / std
max_value = max(max_value, max(normalized_pitch))
min_value = min(min_value, min(normalized_pitch))
utt2pitch[utt] = normalized_pitch
phone_normalized_pitch_path = os.path.join(
processed_dir,
utt_info["Dataset"],
"phone_level_" + pitch_dir,
f'{utt_info["Uid"]}.npy',
)
pitch_statistic = {
"mean": mean,
"std": std,
"min_value": min_value,
"max_value": max_value,
}
else:
spk2utt = {}
pitch_statistic = []
for utt_info in tqdm(meta_data):
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
if not utt2spk[utt] in spk2utt:
spk2utt[utt2spk[utt]] = []
spk2utt[utt2spk[utt]].append(utt)
for spk in spk2utt:
pitch_scaler = StandardScaler()
for utt in spk2utt[spk]:
dataset = utt.split("_")[0]
uid = "_".join(utt.split("_")[1:])
pitch_path = os.path.join(
processed_dir, dataset, pitch_dir, f"{uid}.npy"
)
frame_pitch = np.load(pitch_path)
assert len(frame_pitch) > 0
uv = frame_pitch != 0
utt2uv[utt] = uv
phone_pitch = phone_average_pitch(
frame_pitch, utt2dur[utt], interoperate
)
if use_log_scale:
nonzero_idxes = np.where(phone_pitch != 0)[0]
phone_pitch[nonzero_idxes] = np.log(phone_pitch[nonzero_idxes])
utt2pitch[utt] = phone_pitch
pitch_scaler.partial_fit(remove_outlier(phone_pitch).reshape(-1, 1))
mean, std = pitch_scaler.mean_[0], pitch_scaler.scale_[0]
max_value = np.finfo(np.float64).min
min_value = np.finfo(np.float64).max
if return_norm:
for utt in spk2utt[spk]:
pitch = utt2pitch[utt]
normalized_pitch = (pitch - mean) / std
max_value = max(max_value, max(normalized_pitch))
min_value = min(min_value, min(normalized_pitch))
utt2pitch[utt] = normalized_pitch
pitch_statistic.append(
{
"spk": spk,
"mean": mean,
"std": std,
"min_value": min_value,
"max_value": max_value,
}
)
return utt2pitch, utt2uv, pitch_statistic | null |
17,704 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def load_energy(
meta_data,
processed_dir,
energy_dir,
use_log_scale=False,
return_norm=False,
utt2spk=None,
):
utt2energy = {}
if utt2spk is None:
for utt_info in meta_data:
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
energy_path = os.path.join(
processed_dir, utt_info["Dataset"], energy_dir, f'{utt_info["Uid"]}.npy'
)
if not os.path.exists(energy_path):
continue
energy = np.load(energy_path)
assert len(energy) > 0
if use_log_scale:
nonzero_idxes = np.where(energy != 0)[0]
energy[nonzero_idxes] = np.log(energy[nonzero_idxes])
utt2energy[utt] = energy
if return_norm:
with open(
os.path.join(
processed_dir, utt_info["Dataset"], energy_dir, "statistics.json"
)
) as f:
stats = json.load(f)
mean, std = (
stats[utt_info["Dataset"] + "_" + utt_info["Singer"]][
"voiced_positions"
]["mean"],
stats["LJSpeech_LJSpeech"]["voiced_positions"]["std"],
)
for utt in utt2energy.keys():
energy = utt2energy[utt]
normalized_energy = (energy - mean) / std
utt2energy[utt] = normalized_energy
energy_statistic = {"mean": mean, "std": std}
else:
spk2utt = {}
energy_statistic = []
for utt_info in meta_data:
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
if not utt2spk[utt] in spk2utt:
spk2utt[utt2spk[utt]] = []
spk2utt[utt2spk[utt]].append(utt)
for spk in spk2utt:
energy_scaler = StandardScaler()
for utt in spk2utt[spk]:
dataset = utt.split("_")[0]
uid = "_".join(utt.split("_")[1:])
energy_path = os.path.join(
processed_dir, dataset, energy_dir, f"{uid}.npy"
)
if not os.path.exists(energy_path):
continue
frame_energy = np.load(energy_path)
assert len(frame_energy) > 0
if use_log_scale:
nonzero_idxes = np.where(frame_energy != 0)[0]
frame_energy[nonzero_idxes] = np.log(frame_energy[nonzero_idxes])
utt2energy[utt] = frame_energy
energy_scaler.partial_fit(frame_energy.reshape(-1, 1))
mean, std = energy_scaler.mean_[0], energy_scaler.scale_[0]
if return_norm:
for utt in spk2utt[spk]:
energy = utt2energy[utt]
normalized_energy = (energy - mean) / std
utt2energy[utt] = normalized_energy
energy_statistic.append({"spk": spk, "mean": mean, "std": std})
return utt2energy, energy_statistic | null |
17,705 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def load_frame_energy(
meta_data,
processed_dir,
energy_dir,
use_log_scale=False,
return_norm=False,
interoperate=False,
utt2spk=None,
):
utt2energy = {}
if utt2spk is None:
energy_scaler = StandardScaler()
for utt_info in meta_data:
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
energy_path = os.path.join(
processed_dir, utt_info["Dataset"], energy_dir, f'{utt_info["Uid"]}.npy'
)
frame_energy = np.load(energy_path)
assert len(frame_energy) > 0
if use_log_scale:
nonzero_idxes = np.where(frame_energy != 0)[0]
frame_energy[nonzero_idxes] = np.log(frame_energy[nonzero_idxes])
utt2energy[utt] = frame_energy
energy_scaler.partial_fit(frame_energy.reshape(-1, 1))
mean, std = energy_scaler.mean_[0], energy_scaler.scale_[0]
if return_norm:
for utt_info in meta_data:
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
energy = utt2energy[utt]
normalized_energy = (energy - mean) / std
utt2energy[utt] = normalized_energy
energy_statistic = {"mean": mean, "std": std}
else:
spk2utt = {}
energy_statistic = []
for utt_info in meta_data:
utt = utt_info["Dataset"] + "_" + utt_info["Uid"]
if not utt2spk[utt] in spk2utt:
spk2utt[utt2spk[utt]] = []
spk2utt[utt2spk[utt]].append(utt)
for spk in spk2utt:
energy_scaler = StandardScaler()
for utt in spk2utt[spk]:
dataset = utt.split("_")[0]
uid = "_".join(utt.split("_")[1:])
energy_path = os.path.join(
processed_dir, dataset, energy_dir, f"{uid}.npy"
)
frame_energy = np.load(energy_path)
assert len(frame_energy) > 0
if use_log_scale:
nonzero_idxes = np.where(frame_energy != 0)[0]
frame_energy[nonzero_idxes] = np.log(frame_energy[nonzero_idxes])
utt2energy[utt] = frame_energy
energy_scaler.partial_fit(frame_energy.reshape(-1, 1))
mean, std = energy_scaler.mean_[0], energy_scaler.scale_[0]
if return_norm:
for utt in spk2utt[spk]:
energy = utt2energy[utt]
normalized_energy = (energy - mean) / std
utt2energy[utt] = normalized_energy
energy_statistic.append({"spk": spk, "mean": mean, "std": std})
return utt2energy, energy_statistic | null |
17,706 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def align_length(feature, target_len, pad_value=0.0):
feature_len = feature.shape[-1]
dim = len(feature.shape)
# align 1-D data
if dim == 2:
if target_len > feature_len:
feature = np.pad(
feature,
((0, 0), (0, target_len - feature_len)),
constant_values=pad_value,
)
else:
feature = feature[:, :target_len]
# align 2-D data
elif dim == 1:
if target_len > feature_len:
feature = np.pad(
feature, (0, target_len - feature_len), constant_values=pad_value
)
else:
feature = feature[:target_len]
else:
raise NotImplementedError
return feature | null |
17,707 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def align_whisper_feauture_length(
feature, target_len, fast_mapping=True, source_hop=320, target_hop=256
):
factor = np.gcd(source_hop, target_hop)
source_hop //= factor
target_hop //= factor
# print(
# "Mapping source's {} frames => target's {} frames".format(
# target_hop, source_hop
# )
# )
max_source_len = 1500
target_len = min(target_len, max_source_len * source_hop // target_hop)
width = feature.shape[-1]
if fast_mapping:
source_len = target_len * target_hop // source_hop + 1
feature = feature[:source_len]
else:
source_len = max_source_len
# const ~= target_len * target_hop
const = source_len * source_hop // target_hop * target_hop
# (source_len * source_hop, dim)
up_sampling_feats = np.repeat(feature, source_hop, axis=0)
# (const, dim) -> (const/target_hop, target_hop, dim) -> (const/target_hop, dim)
down_sampling_feats = np.average(
up_sampling_feats[:const].reshape(-1, target_hop, width), axis=1
)
assert len(down_sampling_feats) >= target_len
# (target_len, dim)
feat = down_sampling_feats[:target_len]
return feat | null |
17,708 | import json
import os
import numpy as np
from scipy.interpolate import interp1d
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
def align_content_feature_length(feature, target_len, source_hop=320, target_hop=256):
factor = np.gcd(source_hop, target_hop)
source_hop //= factor
target_hop //= factor
# print(
# "Mapping source's {} frames => target's {} frames".format(
# target_hop, source_hop
# )
# )
# (source_len, 256)
source_len, width = feature.shape
# const ~= target_len * target_hop
const = source_len * source_hop // target_hop * target_hop
# (source_len * source_hop, dim)
up_sampling_feats = np.repeat(feature, source_hop, axis=0)
# (const, dim) -> (const/target_hop, target_hop, dim) -> (const/target_hop, dim)
down_sampling_feats = np.average(
up_sampling_feats[:const].reshape(-1, target_hop, width), axis=1
)
err = abs(target_len - len(down_sampling_feats))
if err > 4: ## why 4 not 3?
print("target_len:", target_len)
print("raw feature:", feature.shape)
print("up_sampling:", up_sampling_feats.shape)
print("down_sampling_feats:", down_sampling_feats.shape)
exit()
if len(down_sampling_feats) < target_len:
# (1, dim) -> (err, dim)
end = down_sampling_feats[-1][None, :].repeat(err, axis=0)
down_sampling_feats = np.concatenate([down_sampling_feats, end], axis=0)
# (target_len, dim)
feat = down_sampling_feats[:target_len]
return feat | null |
17,709 | import torch
import torch.nn.functional as F
from torch.autograd import Variable
from math import exp
def gaussian(window_size, sigma):
gauss = torch.Tensor(
[
exp(-((x - window_size // 2) ** 2) / float(2 * sigma**2))
for x in range(window_size)
]
)
return gauss / gauss.sum()
def create_window(window_size, channel):
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
window = Variable(
_2D_window.expand(channel, 1, window_size, window_size).contiguous()
)
return window | null |
17,710 | import torch
import torch.nn.functional as F
from torch.autograd import Variable
from math import exp
def _ssim(img1, img2, window, window_size, channel, size_average=True):
mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)
mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
sigma1_sq = (
F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq
)
sigma2_sq = (
F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq
)
sigma12 = (
F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel)
- mu1_mu2
)
C1 = 0.01**2
C2 = 0.03**2
ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / (
(mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)
)
if size_average:
return ssim_map.mean()
else:
return ssim_map.mean(1) | null |
17,711 | import numpy as np
import torch
import torch.nn.functional as F
from torch.distributions import Normal
def log_sum_exp(x):
"""numerically stable log_sum_exp implementation that prevents overflow"""
# TF ordering
axis = len(x.size()) - 1
m, _ = torch.max(x, dim=axis)
m2, _ = torch.max(x, dim=axis, keepdim=True)
return m + torch.log(torch.sum(torch.exp(x - m2), dim=axis))
The provided code snippet includes necessary dependencies for implementing the `discretized_mix_logistic_loss` function. Write a Python function `def discretized_mix_logistic_loss( y_hat, y, num_classes=256, log_scale_min=-7.0, reduce=True )` to solve the following problem:
Discretized mixture of logistic distributions loss Note that it is assumed that input is scaled to [-1, 1]. Args: y_hat (Tensor): Predicted output (B x C x T) y (Tensor): Target (B x T x 1). num_classes (int): Number of classes log_scale_min (float): Log scale minimum value reduce (bool): If True, the losses are averaged or summed for each minibatch. Returns Tensor: loss
Here is the function:
def discretized_mix_logistic_loss(
y_hat, y, num_classes=256, log_scale_min=-7.0, reduce=True
):
"""Discretized mixture of logistic distributions loss
Note that it is assumed that input is scaled to [-1, 1].
Args:
y_hat (Tensor): Predicted output (B x C x T)
y (Tensor): Target (B x T x 1).
num_classes (int): Number of classes
log_scale_min (float): Log scale minimum value
reduce (bool): If True, the losses are averaged or summed for each
minibatch.
Returns
Tensor: loss
"""
assert y_hat.dim() == 3
assert y_hat.size(1) % 3 == 0
nr_mix = y_hat.size(1) // 3
# (B x T x C)
y_hat = y_hat.transpose(1, 2)
# unpack parameters. (B, T, num_mixtures) x 3
logit_probs = y_hat[:, :, :nr_mix]
means = y_hat[:, :, nr_mix : 2 * nr_mix]
log_scales = torch.clamp(y_hat[:, :, 2 * nr_mix : 3 * nr_mix], min=log_scale_min)
# B x T x 1 -> B x T x num_mixtures
y = y.expand_as(means)
centered_y = y - means
inv_stdv = torch.exp(-log_scales)
plus_in = inv_stdv * (centered_y + 1.0 / (num_classes - 1))
cdf_plus = torch.sigmoid(plus_in)
min_in = inv_stdv * (centered_y - 1.0 / (num_classes - 1))
cdf_min = torch.sigmoid(min_in)
# log probability for edge case of 0 (before scaling)
# equivalent: torch.log(torch.sigmoid(plus_in))
log_cdf_plus = plus_in - F.softplus(plus_in)
# log probability for edge case of 255 (before scaling)
# equivalent: (1 - torch.sigmoid(min_in)).log()
log_one_minus_cdf_min = -F.softplus(min_in)
# probability for all other cases
cdf_delta = cdf_plus - cdf_min
mid_in = inv_stdv * centered_y
# log probability in the center of the bin, to be used in extreme cases
# (not actually used in our code)
log_pdf_mid = mid_in - log_scales - 2.0 * F.softplus(mid_in)
# tf equivalent
"""
log_probs = tf.where(x < -0.999, log_cdf_plus,
tf.where(x > 0.999, log_one_minus_cdf_min,
tf.where(cdf_delta > 1e-5,
tf.log(tf.maximum(cdf_delta, 1e-12)),
log_pdf_mid - np.log(127.5))))
"""
# TODO: cdf_delta <= 1e-5 actually can happen. How can we choose the value
# for num_classes=65536 case? 1e-7? not sure..
inner_inner_cond = (cdf_delta > 1e-5).float()
inner_inner_out = inner_inner_cond * torch.log(
torch.clamp(cdf_delta, min=1e-12)
) + (1.0 - inner_inner_cond) * (log_pdf_mid - np.log((num_classes - 1) / 2))
inner_cond = (y > 0.999).float()
inner_out = (
inner_cond * log_one_minus_cdf_min + (1.0 - inner_cond) * inner_inner_out
)
cond = (y < -0.999).float()
log_probs = cond * log_cdf_plus + (1.0 - cond) * inner_out
log_probs = log_probs + F.log_softmax(logit_probs, -1)
if reduce:
return -torch.sum(log_sum_exp(log_probs))
else:
return -log_sum_exp(log_probs).unsqueeze(-1) | Discretized mixture of logistic distributions loss Note that it is assumed that input is scaled to [-1, 1]. Args: y_hat (Tensor): Predicted output (B x C x T) y (Tensor): Target (B x T x 1). num_classes (int): Number of classes log_scale_min (float): Log scale minimum value reduce (bool): If True, the losses are averaged or summed for each minibatch. Returns Tensor: loss |
17,712 | import numpy as np
import torch
import torch.nn.functional as F
from torch.distributions import Normal
def to_one_hot(tensor, n, fill_with=1.0):
# we perform one hot encore with respect to the last axis
one_hot = torch.FloatTensor(tensor.size() + (n,)).zero_()
if tensor.is_cuda:
one_hot = one_hot.cuda()
one_hot.scatter_(len(tensor.size()), tensor.unsqueeze(-1), fill_with)
return one_hot
The provided code snippet includes necessary dependencies for implementing the `sample_from_discretized_mix_logistic` function. Write a Python function `def sample_from_discretized_mix_logistic(y, log_scale_min=-7.0, clamp_log_scale=False)` to solve the following problem:
Sample from discretized mixture of logistic distributions Args: y (Tensor): B x C x T log_scale_min (float): Log scale minimum value Returns: Tensor: sample in range of [-1, 1].
Here is the function:
def sample_from_discretized_mix_logistic(y, log_scale_min=-7.0, clamp_log_scale=False):
"""
Sample from discretized mixture of logistic distributions
Args:
y (Tensor): B x C x T
log_scale_min (float): Log scale minimum value
Returns:
Tensor: sample in range of [-1, 1].
"""
assert y.size(1) % 3 == 0
nr_mix = y.size(1) // 3
# B x T x C
y = y.transpose(1, 2)
logit_probs = y[:, :, :nr_mix]
# sample mixture indicator from softmax
temp = logit_probs.data.new(logit_probs.size()).uniform_(1e-5, 1.0 - 1e-5)
temp = logit_probs.data - torch.log(-torch.log(temp))
_, argmax = temp.max(dim=-1)
# (B, T) -> (B, T, nr_mix)
one_hot = to_one_hot(argmax, nr_mix)
# select logistic parameters
means = torch.sum(y[:, :, nr_mix : 2 * nr_mix] * one_hot, dim=-1)
log_scales = torch.sum(y[:, :, 2 * nr_mix : 3 * nr_mix] * one_hot, dim=-1)
if clamp_log_scale:
log_scales = torch.clamp(log_scales, min=log_scale_min)
# sample from logistic & clip to interval
# we don't actually round to the nearest 8bit value when sampling
u = means.data.new(means.size()).uniform_(1e-5, 1.0 - 1e-5)
x = means + torch.exp(log_scales) * (torch.log(u) - torch.log(1.0 - u))
x = torch.clamp(torch.clamp(x, min=-1.0), max=1.0)
return x | Sample from discretized mixture of logistic distributions Args: y (Tensor): B x C x T log_scale_min (float): Log scale minimum value Returns: Tensor: sample in range of [-1, 1]. |
17,713 | import numpy as np
import torch
import torch.nn.functional as F
from torch.distributions import Normal
def log_sum_exp(x):
"""numerically stable log_sum_exp implementation that prevents overflow"""
# TF ordering
axis = len(x.size()) - 1
m, _ = torch.max(x, dim=axis)
m2, _ = torch.max(x, dim=axis, keepdim=True)
return m + torch.log(torch.sum(torch.exp(x - m2), dim=axis))
The provided code snippet includes necessary dependencies for implementing the `mix_gaussian_loss` function. Write a Python function `def mix_gaussian_loss(y_hat, y, log_scale_min=-7.0, reduce=True)` to solve the following problem:
Mixture of continuous gaussian distributions loss Note that it is assumed that input is scaled to [-1, 1]. Args: y_hat (Tensor): Predicted output (B x C x T) y (Tensor): Target (B x T x 1). log_scale_min (float): Log scale minimum value reduce (bool): If True, the losses are averaged or summed for each minibatch. Returns Tensor: loss
Here is the function:
def mix_gaussian_loss(y_hat, y, log_scale_min=-7.0, reduce=True):
"""Mixture of continuous gaussian distributions loss
Note that it is assumed that input is scaled to [-1, 1].
Args:
y_hat (Tensor): Predicted output (B x C x T)
y (Tensor): Target (B x T x 1).
log_scale_min (float): Log scale minimum value
reduce (bool): If True, the losses are averaged or summed for each
minibatch.
Returns
Tensor: loss
"""
assert y_hat.dim() == 3
C = y_hat.size(1)
if C == 2:
nr_mix = 1
else:
assert y_hat.size(1) % 3 == 0
nr_mix = y_hat.size(1) // 3
# (B x T x C)
y_hat = y_hat.transpose(1, 2)
# unpack parameters.
if C == 2:
# special case for C == 2, just for compatibility
logit_probs = None
means = y_hat[:, :, 0:1]
log_scales = torch.clamp(y_hat[:, :, 1:2], min=log_scale_min)
else:
# (B, T, num_mixtures) x 3
logit_probs = y_hat[:, :, :nr_mix]
means = y_hat[:, :, nr_mix : 2 * nr_mix]
log_scales = torch.clamp(
y_hat[:, :, 2 * nr_mix : 3 * nr_mix], min=log_scale_min
)
# B x T x 1 -> B x T x num_mixtures
y = y.expand_as(means)
centered_y = y - means
dist = Normal(loc=0.0, scale=torch.exp(log_scales))
# do we need to add a trick to avoid log(0)?
log_probs = dist.log_prob(centered_y)
if nr_mix > 1:
log_probs = log_probs + F.log_softmax(logit_probs, -1)
if reduce:
if nr_mix == 1:
return -torch.sum(log_probs)
else:
return -torch.sum(log_sum_exp(log_probs))
else:
if nr_mix == 1:
return -log_probs
else:
return -log_sum_exp(log_probs).unsqueeze(-1) | Mixture of continuous gaussian distributions loss Note that it is assumed that input is scaled to [-1, 1]. Args: y_hat (Tensor): Predicted output (B x C x T) y (Tensor): Target (B x T x 1). log_scale_min (float): Log scale minimum value reduce (bool): If True, the losses are averaged or summed for each minibatch. Returns Tensor: loss |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.