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.... | 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_tensor... | 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... |
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... | 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.F... | 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... |
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 neces... | 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 neces... | 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 ... | 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 neces... | 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 neces... | 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 neces... | 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):
l... | 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_output... | 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):
l... | 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.gener... | 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_fiel... | 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="re... | 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 ... | 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_datase... | 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 ... | 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_si... | 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.... | 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... | 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_siz... | 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, fr... | 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, frame... | 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:... | 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.to... | 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: No... |
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.d... | 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:
... | 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,
BaseTes... | 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: No... |
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 ... | 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"... | 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(pr... | 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... | 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 Tra... | 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 Tra... | 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 Tra... | 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_datase... | 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_confi... | 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_confi... | 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 cod... | 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, SEANetRe... | 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 inc... | 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... | 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, low... | 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_m... | 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:... | 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... | 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(
g... | 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(mode... | 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(mod... | 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 inc... | 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,... | 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, ... | 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,... | 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):
... | 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_mu... | 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_shap... | 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_(paramete... | 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():
p... | 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 inc... | 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, ... |
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 (b... | 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.... |
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... | 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_i... | 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")
... | 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(utt2s... | 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 = ... | 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 *... | 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,... | 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,
):
... | 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,... | 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 utt2s... | 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,
):
... | 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 ... | 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_... | 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_... | 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 / gau... | 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=chan... | 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, ke... | 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 averag... |
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.cu... | 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, ke... | 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. Retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.