id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
17,405
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time class PathConfig: """ Helper class containing constants for various...
Returns the user's Twitter username from account.js.
17,406
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time The provided code snippet includes necessary dependencies for implementing...
Identify the tweet archive's file and folder names - they change slightly depending on the archive size it seems.
17,407
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time def find_dir_input_media(dir_path_input_data): input_media_dir_templat...
null
17,408
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time class PathConfig: """ Helper class containing constants for various...
Uses (filename, URL) tuples in media_sources to download files from remote storage. Aborts downloads if the remote file is the same size or smaller than the existing local version. Retries the failed downloads several times, with increasing pauses between each to avoid being blocked.
17,409
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time class PathConfig: """ Helper class containing constants for various...
Read tweets from paths.files_input_tweets, write to *.md and *.html. Copy the media used to paths.dir_output_media. Collect user_id:user_handle mappings for later use, in 'users'. Returns the mapping from media filename to best-quality URL.
17,410
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time def read_json_from_js_file(filename): """Reads the contents of a Twitte...
Collect all user ids that appear in the followings archive data. (For use in bulk online lookup from Twitter.)
17,411
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time class PathConfig: """ Helper class containing constants for various...
Parse paths.dir_input_data/following.js, write to paths.file_output_following.
17,412
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time def read_json_from_js_file(filename): """Reads the contents of a Twitte...
Collect all user ids that appear in the followers archive data. (For use in bulk online lookup from Twitter.)
17,413
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time class PathConfig: """ Helper class containing constants for various...
Parse paths.dir_input_data/followers.js, write to paths.file_output_followers.
17,414
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time def read_json_from_js_file(filename): """Reads the contents of a Twitte...
Collect all user ids that appear in the direct messages archive data. (For use in bulk online lookup from Twitter.)
17,415
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time class PathConfig: """ Helper class containing constants for various...
Parse paths.dir_input_data/direct-messages.js, write to one markdown file per conversation.
17,416
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time def read_json_from_js_file(filename): """Reads the contents of a Twitte...
Collect all user ids that appear in the group direct messages archive data. (For use in bulk online lookup from Twitter.)
17,417
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time def open_and_mkdirs(path_file): """Opens a file for writing. If the par...
Parse data_folder/direct-messages-group.js, write to one markdown file per conversation.
17,418
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time class PathConfig: """ Helper class containing constants for various...
If present, moves media and cache files from the archive root to the new locations in `paths.dir_output_media` and `paths.dir_output_cache`. Then deletes old output files (md, html, txt) from the archive root, if the user consents.
17,419
from collections import defaultdict from typing import Optional from urllib.parse import urlparse import datetime import glob import importlib import json import logging import os import re import shutil import subprocess import sys import time def is_archive(path): """Return true if there is a Twitter archive at t...
Search for the archive 1. First try the working directory. 2. Then try the script directory. 3. Finally prompt the user.
17,420
import torch import torch.nn as nn import einops from torch.nn.utils import spectral_norm, weight_norm CONV_NORMALIZATIONS = frozenset( [ "none", "weight_norm", "spectral_norm", "time_layer_norm", "layer_norm", "time_group_norm", ] ) def apply_parametrization_nor...
null
17,421
import torch import torch.nn as nn import einops from torch.nn.utils import spectral_norm, weight_norm CONV_NORMALIZATIONS = frozenset( [ "none", "weight_norm", "spectral_norm", "time_layer_norm", "layer_norm", "time_group_norm", ] ) class ConvLayerNorm(nn.LayerNo...
Return the proper normalization module. If causal is True, this will ensure the returned module is causal, or return an error if the normalization doesn't support causal evaluation.
17,422
import typing as tp def get_padding(kernel_size, dilation=1): return int((kernel_size * dilation - dilation) / 2)
null
17,423
import typing as tp 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,424
import typing as tp 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,425
from typing import Optional import six import torch import numpy as np def sequence_mask( lengths, maxlen: Optional[int] = None, dtype: torch.dtype = torch.float32, device: Optional[torch.device] = None, ) -> torch.Tensor: if maxlen is None: maxlen = lengths.max() row_vector = torch.ara...
null
17,426
from typing import Optional import six import torch import numpy as np The provided code snippet includes necessary dependencies for implementing the `end_detect` function. Write a Python function `def end_detect(ended_hyps, i, M=3, d_end=np.log(1 * np.exp(-10)))` to solve the following problem: End detection. describ...
End detection. described in Eq. (50) of S. Watanabe et al "Hybrid CTC/Attention Architecture for End-to-End Speech Recognition" :param ended_hyps: :param i: :param M: :param d_end: :return:
17,427
from itertools import chain from typing import Any from typing import Dict from typing import List from typing import Tuple from typing import Union from typing import NamedTuple import torch from modules.wenet_extractor.paraformer.utils import end_detect from modules.wenet_extractor.paraformer.search.ctc import CTCPre...
null
17,428
from typing import Optional import torch from torch import nn from modules.wenet_extractor.utils.mask import make_pad_mask def cif(hidden: torch.Tensor, alphas: torch.Tensor, threshold: float): batch_size, len_time, hidden_size = hidden.size() # loop varss integrate = torch.zeros([batch_size], device=hidd...
null
17,429
from typing import List import torch def basic_greedy_search( model: torch.nn.Module, encoder_out: torch.Tensor, encoder_out_lens: torch.Tensor, n_steps: int = 64, ) -> List[List[int]]: # fake padding padding = torch.zeros(1, 1).to(encoder_out.device) # sos pred_input_step = torch.tenso...
null
17,430
from typing import List, Optional, Tuple import torch from torch import nn from modules.wenet_extractor.utils.common import get_activation, get_rnn The provided code snippet includes necessary dependencies for implementing the `ApplyPadding` function. Write a Python function `def ApplyPadding(input, padding, pad_value...
Args: input: [bs, max_time_step, dim] padding: [bs, max_time_step]
17,431
import numpy as np import torch def insert_blank(label, blank_id=0): """Insert blank token between every two label token.""" label = np.expand_dims(label, 1) blanks = np.zeros((label.shape[0], 1), dtype=np.int64) + blank_id label = np.concatenate([blanks, label], axis=1) label = label.reshape(-1) ...
ctc forced alignment. Args: torch.Tensor ctc_probs: hidden state sequence, 2d tensor (T, D) torch.Tensor y: id sequence tensor 1d tensor (L) int blank_id: blank symbol index Returns: torch.Tensor: alignment result
17,432
import torch The provided code snippet includes necessary dependencies for implementing the `subsequent_mask` function. Write a Python function `def subsequent_mask( size: int, device: torch.device = torch.device("cpu"), ) -> torch.Tensor` to solve the following problem: Create mask for subsequent steps (size,...
Create mask for subsequent steps (size, size). This mask is used only in decoder which works in an auto-regressive mode. This means the current step could only do attention with its left steps. In encoder, fully attention is used when streaming is not necessary and the sequence is not long. In this case, no attention m...
17,433
import torch def subsequent_chunk_mask( size: int, chunk_size: int, num_left_chunks: int = -1, device: torch.device = torch.device("cpu"), ) -> torch.Tensor: """Create mask for subsequent steps (size, size) with chunk size, this is for streaming encoder Args: size (int): size of m...
Apply optional mask for encoder. Args: xs (torch.Tensor): padded input, (B, L, D), L for max length mask (torch.Tensor): mask for xs, (B, 1, L) use_dynamic_chunk (bool): whether to use dynamic chunk or not use_dynamic_left_chunk (bool): whether to use dynamic left chunk for training. decoding_chunk_size (int): decoding...
17,434
import torch def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor: """Make mask tensor containing indices of padded part. See description of make_non_pad_mask. Args: lengths (torch.Tensor): Batch of lengths (B,). Returns: torch.Tensor: Mask tensor containing indices...
Make mask tensor containing indices of non-padded part. The sequences in a batch may have different lengths. To enable batch computing, padding is need to make all sequence in same size. To avoid the padding part pass value to context dependent block such as attention or convolution , this padding part is masked. This ...
17,435
import torch The provided code snippet includes necessary dependencies for implementing the `mask_finished_scores` function. Write a Python function `def mask_finished_scores(score: torch.Tensor, flag: torch.Tensor) -> torch.Tensor` to solve the following problem: If a sequence is finished, we only allow one alive bra...
If a sequence is finished, we only allow one alive branch. This function aims to give one branch a zero score and the rest -inf score. Args: score (torch.Tensor): A real value array with shape (batch_size * beam_size, beam_size). flag (torch.Tensor): A bool array with shape (batch_size * beam_size, 1). Returns: torch.T...
17,436
import torch The provided code snippet includes necessary dependencies for implementing the `mask_finished_preds` function. Write a Python function `def mask_finished_preds( pred: torch.Tensor, flag: torch.Tensor, eos: int ) -> torch.Tensor` to solve the following problem: If a sequence is finished, all of its bra...
If a sequence is finished, all of its branch should be <eos> Args: pred (torch.Tensor): A int array with shape (batch_size * beam_size, beam_size). flag (torch.Tensor): A bool array with shape (batch_size * beam_size, 1). Returns: torch.Tensor: (batch_size * beam_size).
17,437
import re def read_lists(list_file): lists = [] with open(list_file, "r", encoding="utf8") as fin: for line in fin: lists.append(line.strip()) return lists The provided code snippet includes necessary dependencies for implementing the `read_non_lang_symbols` function. Write a Python fun...
read non-linguistic symbol from file. The file format is like below: {NOISE}\n {BRK}\n ... Args: non_lang_sym_path: non-linguistic symbol file path, None means no any syms.
17,438
import re def read_symbol_table(symbol_table_file): symbol_table = {} with open(symbol_table_file, "r", encoding="utf8") as fin: for line in fin: arr = line.strip().split() assert len(arr) == 2 symbol_table[arr[0]] = int(arr[1]) return symbol_table
null
17,439
import torch from modules.wenet_extractor.transducer.joint import TransducerJoint from modules.wenet_extractor.transducer.predictor import ( ConvPredictor, EmbeddingPredictor, RNNPredictor, ) from modules.wenet_extractor.transducer.transducer import Transducer from modules.wenet_extractor.transformer.asr_mo...
null
17,440
import logging import os import re import yaml import torch from collections import OrderedDict import datetime def load_checkpoint(model: torch.nn.Module, path: str) -> dict: if torch.cuda.is_available(): logging.info("Checkpoint: loading from checkpoint %s for GPU" % path) checkpoint = torch.load...
null
17,441
import logging import os import re import yaml import torch from collections import OrderedDict import datetime The provided code snippet includes necessary dependencies for implementing the `save_checkpoint` function. Write a Python function `def save_checkpoint(model: torch.nn.Module, path: str, infos=None)` to solv...
Args: infos (dict or None): any info you want to save.
17,442
import logging import os import re import yaml import torch from collections import OrderedDict import datetime def filter_modules(model_state_dict, modules): new_mods = [] incorrect_mods = [] mods_model = model_state_dict.keys() for mod in modules: if any(key.startswith(mod) for key in mods_mod...
null
17,443
import copy def override_config(configs, override_list): new_configs = copy.deepcopy(configs) for item in override_list: arr = item.split() if len(arr) != 2: print(f"the overrive {item} format not correct, skip it") continue keys = arr[0].split(".") s_con...
null
17,444
from typing import Union import math import warnings import torch from torch.optim.lr_scheduler import _LRScheduler def _squareroot_annealing(initial_lr, step, max_steps, min_lr): mult = ((max_steps - step) / max_steps) ** 0.5 out_lr = initial_lr * mult out_lr = max(out_lr, min_lr) return out_lr
null
17,445
from typing import Union import math import warnings import torch from torch.optim.lr_scheduler import _LRScheduler def _square_annealing(initial_lr, step, max_steps, min_lr): mult = ((max_steps - step) / max_steps) ** 2 out_lr = initial_lr * mult out_lr = max(out_lr, min_lr) return out_lr
null
17,446
from typing import Union import math import warnings import torch from torch.optim.lr_scheduler import _LRScheduler def _cosine_annealing(initial_lr, step, max_steps, min_lr): mult = 0.5 * (1 + math.cos(math.pi * step / max_steps)) out_lr = (initial_lr - min_lr) * mult + min_lr return out_lr
null
17,447
from typing import Union import math import warnings import torch from torch.optim.lr_scheduler import _LRScheduler def _linear_warmup_with_cosine_annealing( max_lr, warmup_steps, step, decay_steps, min_lr ): assert max_lr > min_lr # Use linear warmup for the initial part. if warmup_steps > 0 and step ...
null
17,448
from typing import Union import math import warnings import torch from torch.optim.lr_scheduler import _LRScheduler def _poly_decay(initial_lr, step, decay_steps, power, min_lr, cycle): if cycle: multiplier = 1.0 if step == 0 else math.ceil(step / decay_steps) decay_steps *= multiplier else: ...
null
17,449
from typing import Union import math import warnings import torch from torch.optim.lr_scheduler import _LRScheduler def _noam_hold_annealing( initial_lr, step, warmup_steps, hold_steps, decay_rate, min_lr ): # hold_steps = total number of steps # to hold the LR, not the warmup + hold steps. T_warmup_de...
null
17,450
import math from typing import List, Tuple import torch from torch.nn.utils.rnn import pad_sequence The provided code snippet includes necessary dependencies for implementing the `add_blank` function. Write a Python function `def add_blank(ys_pad: torch.Tensor, blank: int, ignore_id: int) -> torch.Tensor` to solve the...
Prepad blank for transducer predictor Args: ys_pad (torch.Tensor): batch of padded target sequences (B, Lmax) blank (int): index of <blank> Returns: ys_in (torch.Tensor) : (B, Lmax + 1) Examples: >>> blank = 0 >>> ignore_id = -1 >>> ys_pad tensor([[ 1, 2, 3, 4, 5], [ 4, 5, 6, -1, -1], [ 7, 8, 9, -1, -1]], dtype=torch.i...
17,451
import math from typing import List, Tuple import torch from torch.nn.utils.rnn import pad_sequence def pad_list(xs: List[torch.Tensor], pad_value: int): """Perform padding for the list of tensors. Args: xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)]. pad_value (float): Val...
Add <sos> and <eos> labels. Args: ys_pad (torch.Tensor): batch of padded target sequences (B, Lmax) sos (int): index of <sos> eos (int): index of <eeos> ignore_id (int): index of padding Returns: ys_in (torch.Tensor) : (B, Lmax + 1) ys_out (torch.Tensor) : (B, Lmax + 1) Examples: >>> sos_id = 10 >>> eos_id = 11 >>> ign...
17,452
import math from typing import List, Tuple import torch from torch.nn.utils.rnn import pad_sequence The provided code snippet includes necessary dependencies for implementing the `reverse_pad_list` function. Write a Python function `def reverse_pad_list( ys_pad: torch.Tensor, ys_lens: torch.Tensor, pad_value: floa...
Reverse padding for the list of tensors. Args: ys_pad (tensor): The padded tensor (B, Tokenmax). ys_lens (tensor): The lens of token seqs (B) pad_value (int): Value for padding. Returns: Tensor: Padded tensor (B, Tokenmax). Examples: >>> x tensor([[1, 2, 3, 4], [5, 6, 7, 0], [8, 9, 0, 0]]) >>> pad_list(x, 0) tensor([[4...
17,453
import math from typing import List, Tuple import torch from torch.nn.utils.rnn import pad_sequence The provided code snippet includes necessary dependencies for implementing the `th_accuracy` function. Write a Python function `def th_accuracy( pad_outputs: torch.Tensor, pad_targets: torch.Tensor, ignore_label: in...
Calculate accuracy. Args: pad_outputs (Tensor): Prediction tensors (B * Lmax, D). pad_targets (LongTensor): Target label tensors (B, Lmax). ignore_label (int): Ignore label id. Returns: float: Accuracy value (0.0 - 1.0).
17,454
import math from typing import List, Tuple import torch from torch.nn.utils.rnn import pad_sequence def get_rnn(rnn_type: str) -> torch.nn.Module: assert rnn_type in ["rnn", "lstm", "gru"] if rnn_type == "rnn": return torch.nn.RNN elif rnn_type == "lstm": return torch.nn.LSTM else: ...
null
17,455
import math from typing import List, Tuple import torch from torch.nn.utils.rnn import pad_sequence class Swish(torch.nn.Module): """Construct an Swish object.""" def forward(self, x: torch.Tensor) -> torch.Tensor: """Return Swish activation function.""" return x * torch.sigmoid(x) The provid...
Return activation function.
17,456
import math from typing import List, Tuple import torch from torch.nn.utils.rnn import pad_sequence def get_subsample(config): input_layer = config["encoder_conf"]["input_layer"] assert input_layer in ["conv2d", "conv2d6", "conv2d8"] if input_layer == "conv2d": return 4 elif input_layer == "con...
null
17,457
import math from typing import List, Tuple import torch from torch.nn.utils.rnn import pad_sequence def remove_duplicates_and_blank(hyp: List[int]) -> List[int]: new_hyp: List[int] = [] cur = 0 while cur < len(hyp): if hyp[cur] != 0: new_hyp.append(hyp[cur]) prev = cur w...
null
17,458
import math from typing import List, Tuple import torch from torch.nn.utils.rnn import pad_sequence def replace_duplicates_with_blank(hyp: List[int]) -> List[int]: new_hyp: List[int] = [] cur = 0 while cur < len(hyp): new_hyp.append(hyp[cur]) prev = cur cur += 1 while cur < ...
null
17,459
import math from typing import List, Tuple import torch from torch.nn.utils.rnn import pad_sequence The provided code snippet includes necessary dependencies for implementing the `log_add` function. Write a Python function `def log_add(args: List[int]) -> float` to solve the following problem: Stable log add Here is ...
Stable log add
17,460
import torch import torch.nn as nn import torch.nn.functional as F import math if "sinc" in dir(torch): sinc = torch.sinc else: # This code is adopted from adefossez's julius.core.sinc under the MIT License # https://adefossez.github.io/julius/julius/core.html def sinc(x: torch.Tensor): """ ...
null
17,461
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `normalization` function. Write a Python function `def normalization(channels: int, groups: int = 32)` to solve the following problem: r"""Make a standard normalization layer, i.e. GroupNorm. Args: channel...
r"""Make a standard normalization layer, i.e. GroupNorm. Args: channels: number of input channels. groups: number of groups for group normalization. Returns: a ``nn.Module`` for normalization.
17,462
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `Linear` function. Write a Python function `def Linear(*args, **kwargs)` to solve the following problem: r"""Wrapper of ``nn.Linear`` with kaiming_normal_ initialization. Here is the function: def Linear...
r"""Wrapper of ``nn.Linear`` with kaiming_normal_ initialization.
17,463
import torch import torch.nn as nn def Conv1d(*args, **kwargs): r"""Wrapper of ``nn.Conv1d`` with kaiming_normal_ initialization.""" layer = nn.Conv1d(*args, **kwargs) nn.init.kaiming_normal_(layer.weight) return layer def Conv2d(*args, **kwargs): r"""Wrapper of ``nn.Conv2d`` with kaiming_normal_ in...
r"""Wrapper of N-dimension convolution with kaiming_normal_ initialization. Args: dims: number of dimensions of the convolution.
17,464
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `zero_module` function. Write a Python function `def zero_module(module: nn.Module)` to solve the following problem: r"""Zero out the parameters of a module and return it. Here is the function: def zero_...
r"""Zero out the parameters of a module and return it.
17,465
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `scale_module` function. Write a Python function `def scale_module(module: nn.Module, scale)` to solve the following problem: r"""Scale the parameters of a module and return it. Here is the function: def...
r"""Scale the parameters of a module and return it.
17,466
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `mean_flat` function. Write a Python function `def mean_flat(tensor: torch.Tensor)` to solve the following problem: r"""Take the mean over all non-batch dimensions. Here is the function: def mean_flat(te...
r"""Take the mean over all non-batch dimensions.
17,467
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `append_dims` function. Write a Python function `def append_dims(x, target_dims)` to solve the following problem: r"""Appends dimensions to the end of a tensor until it has target_dims dimensions. Here is...
r"""Appends dimensions to the end of a tensor until it has target_dims dimensions.
17,468
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `append_zero` function. Write a Python function `def append_zero(x, count=1)` to solve the following problem: r"""Appends ``count`` zeros to the end of a tensor along the last dimension. Here is the funct...
r"""Appends ``count`` zeros to the end of a tensor along the last dimension.
17,469
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor def _compute_scale_factor( x: Tensor, channel_dim: int, min_abs: float, max_abs: float, gain_factor: float, max_factor: float, ) -> Tensor: if chann...
null
17,470
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor def _compute_sign_factor( x: Tensor, channel_dim: int, min_positive: float, max_positive: float, gain_factor: float, max_factor: float, ) -> Tensor: ...
null
17,471
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class RandomClampFunction(torch.autograd.Function): def forward( ctx, x: Tensor, min: Optional[float], max: Optional[float], prob: fl...
null
17,472
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `random_cast_to_half` function. Write a Python function `def random_cast_to_half(x: Tensor, min_a...
A randomized way of casting a floating point value to half precision.
17,473
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `ScaledLinear` function. Write a Python function `def ScaledLinear(*args, initial_scale: float = ...
Behaves like a constructor of a modified version of nn.Linear that gives an easy way to set the default initial parameter scale. Args: Accepts the standard args and kwargs that nn.Linear accepts e.g. in_features, out_features, bias=False. initial_scale: you can override this if you want to increase or decrease the init...
17,474
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class Transpose(nn.Identity): """(N, T, D) -> (N, D, T)""" def forward(self, input: torch.Tensor) -> torch.Tensor: return input.transpose(1, 2) def ScaledConv1d(...
Transpose -> ScaledConv1d
17,475
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class Transpose(nn.Identity): """(N, T, D) -> (N, D, T)""" def forward(self, input: torch.Tensor) -> torch.Tensor: return input.transpose(1, 2) def ScaledConv1d(...
Transpose -> ScaledConv1d
17,476
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class Transpose(nn.Identity): """(N, T, D) -> (N, D, T)""" def forward(self, input: torch.Tensor) -> torch.Tensor: return input.transpose(1, 2) The provided cod...
Transpose -> Conv1d
17,477
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class Transpose(nn.Identity): """(N, T, D) -> (N, D, T)""" def forward(self, input: torch.Tensor) -> torch.Tensor: return input.transpose(1, 2) The provided cod...
ScaledConv1d -> Transpose
17,478
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class Transpose(nn.Identity): """(N, T, D) -> (N, D, T)""" def forward(self, input: torch.Tensor) -> torch.Tensor: return input.transpose(1, 2) class SRConv1d(SR...
Transpose -> SRConv1d
17,479
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class Transpose(nn.Identity): """(N, T, D) -> (N, D, T)""" def forward(self, input: torch.Tensor) -> torch.Tensor: return input.transpose(1, 2) class SRConv1d(SR...
SRConv1d -> Transpose
17,480
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor def with_loss(x, y): if torch.jit.is_scripting() or torch.jit.is_tracing(): return x # returns x but adds y.sum() to the loss function. return WithLoss.apply...
Returns x unmodified, but in backprop will put a penalty for the excess of the absolute values of elements of x over the limit "limit". E.g. if limit == 10.0, then if x has any values over 10 it will get a penalty. Caution: the value of this penalty will be affected by grad scaling used in automatic mixed precision tra...
17,481
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor def _diag(x: Tensor): # like .diag(), but works for tensors with 3 dims. if x.ndim == 2: return x.diag() else: (batch, dim, dim) = x.shape x = x...
Computes the "whitening metric", a value which will be 1.0 if all the eigenvalues of of the centered feature covariance are the same within each group's covariance matrix and also between groups. Args: x: a Tensor of shape (*, num_channels) num_groups: the number of groups of channels, a number >=1 that divides num_cha...
17,482
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor def _no_op(x: Tensor) -> Tensor: if torch.jit.is_scripting() or torch.jit.is_tracing(): return x else: # a no-op function that will have a node in the a...
null
17,483
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class ActivationBalancer(torch.nn.Module): """ Modifies the backpropped derivatives of a function to try to encourage, for each channel, that it is positive at least...
ActivationBalancer -> DoubleSwish
17,484
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class MaxEig(torch.nn.Module): """ Modifies the backpropped derivatives of a function to try to discourage that any given direction in activation space accounts for ...
null
17,485
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class Whiten(nn.Module): def __init__( self, num_groups: int, whitening_limit: float, prob: Union[float, Tuple[float, float]], grad_s...
null
17,486
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class ActivationBalancer(torch.nn.Module): def __init__( self, num_channels: int, channel_dim: int, min_positive: float = 0....
null
17,487
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class ActivationBalancer(torch.nn.Module): """ Modifies the backpropped derivatives of a function to try to encourage, for each channel, that it is positive at least...
null
17,488
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class BasicNorm(torch.nn.Module): """ This is intended to be a simpler, and hopefully cheaper, replacement for LayerNorm. The observation this is based on, is that ...
null
17,489
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor class DoubleSwish(torch.nn.Module): def forward(self, x: Tensor) -> Tensor: """Return double-swish activation function which is an approximation to Swish(Swish(x)), ...
null
17,490
import logging import random import math from typing import Optional, Tuple, Union import torch import torch.nn as nn from torch import Tensor def softmax(x: Tensor, dim: int): if torch.jit.is_scripting() or torch.jit.is_tracing(): return x.softmax(dim) return SoftmaxFunction.apply(x, dim) def _test_so...
null
17,491
import math import torch from torch import nn from torch.nn import Parameter import torch.nn.functional as F import numpy as np 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))]) ou...
null
17,492
import torch from torch.nn import functional as F import numpy as np DEFAULT_MIN_BIN_WIDTH = 1e-3 DEFAULT_MIN_BIN_HEIGHT = 1e-3 DEFAULT_MIN_DERIVATIVE = 1e-3 def unconstrained_rational_quadratic_spline( inputs, unnormalized_widths, unnormalized_heights, unnormalized_derivatives, inverse=False, t...
null
17,493
import copy from functools import partial from typing import Any, Callable, List, Optional, Union import torch from torch import Tensor, nn from torch.nn import functional as F from modules.norms import AdaptiveLayerNorm, LayerNorm, BalancedBasicNorm, IdentityNorm from modules.transformer import MultiheadAttention from...
null
17,494
import copy from functools import partial from typing import Any, Callable, List, Optional, Union import torch from torch import Tensor, nn from torch.nn import functional as F from modules.norms import AdaptiveLayerNorm, LayerNorm, BalancedBasicNorm, IdentityNorm from modules.transformer import MultiheadAttention from...
null
17,495
import torch import torch.nn as nn import numpy as np from .Layers import FFTBlock from text.symbols import symbols The provided code snippet includes necessary dependencies for implementing the `get_sinusoid_encoding_table` function. Write a Python function `def get_sinusoid_encoding_table(n_position, d_hid, padding_...
Sinusoid position encoding table
17,496
from abc import ABC, abstractmethod import numpy as np import torch as th from scipy.stats import norm import torch.distributed as dist class UniformSampler(ScheduleSampler): def __init__(self, diffusion): self.diffusion = diffusion self._weights = np.ones([diffusion.num_timesteps]) def weights(...
Create a ScheduleSampler from a library of pre-defined samplers. :param name: the name of the sampler. :param diffusion: the diffusion object to sample for.
17,497
import random import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from utils.ssim import SSIM from modules.diffusion.karras.random_utils import get_generator The provided code snippet includes necessary dependencies for implementing the `mean_flat` function. Write a Python funct...
Take the mean over all non-batch dimensions.
17,498
import random import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from utils.ssim import SSIM from modules.diffusion.karras.random_utils import get_generator def get_weightings(weight_schedule, snrs, sigma_data): if weight_schedule == "snr": weightings = snrs eli...
null
17,499
import random import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from utils.ssim import SSIM from modules.diffusion.karras.random_utils import get_generator def get_sigmas_karras(n, sigma_min, sigma_max, rho=7.0, device="cpu"): """Constructs the noise schedule of Karras et a...
null
17,500
import random import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from utils.ssim import SSIM from modules.diffusion.karras.random_utils import get_generator The provided code snippet includes necessary dependencies for implementing the `sample_midpoint_ancestral` function. Writ...
Ancestral sampling with midpoint method steps.
17,502
import re from g2p_en import G2p from string import punctuation def read_lexicon(lex_path): lexicon = {} with open(lex_path) as f: for line in f: temp = re.split(r"\s+", line.strip("\n")) word = temp[0] phones = temp[1:] if word.lower() not in lexicon: ...
null
17,503
import re from g2p_en import G2p from string import punctuation def preprocess_english(text, lexicon): text = text.rstrip(punctuation) g2p = G2p() phones = [] words = re.split(r"([,;.\-\?\!\s+])", text) for w in words: if w.lower() in lexicon: phones += lexicon[w.lower()] ...
null
17,504
import re from unidecode import unidecode from .numbers import normalize_numbers def lowercase(text): return text.lower() def collapse_whitespace(text): return re.sub(_whitespace_re, " ", text) The provided code snippet includes necessary dependencies for implementing the `basic_cleaners` function. Write a Pyt...
Basic pipeline that lowercases and collapses whitespace without transliteration.
17,505
import re from unidecode import unidecode from .numbers import normalize_numbers def lowercase(text): return text.lower() def collapse_whitespace(text): return re.sub(_whitespace_re, " ", text) def convert_to_ascii(text): return unidecode(text) The provided code snippet includes necessary dependencies for ...
Pipeline for non-English text that transliterates to ASCII.