id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
18,956 | from collections import namedtuple
import random
import os
import csv
import torch
import nltk
from nltk import tokenize as nltk_tokenize
import sentencepiece as spm
from .wordpiece import BertTokenizer, PRETRAINED_VOCAB_ARCHIVE_MAP
from .tokenization_gpt2 import GPT2Tokenizer
import regex as re
class TypeToken(object)... | null |
18,969 | import torch
from torch import nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
FLOAT_TYPES = (torch.FloatTensor, torch.cuda.FloatTensor)
def conversion_helper(val, conversion):
"""Apply conversion to val. Recursively apply conversion if `val` is a nested tuple/list structure."""
... | Convert fp32 `val` to fp16 |
18,970 | import torch
from torch import nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
HALF_TYPES = (torch.HalfTensor, torch.cuda.HalfTensor)
def conversion_helper(val, conversion):
"""Apply conversion to val. Recursively apply conversion if `val` is a nested tuple/list structure."""
if ... | Convert fp16 `val` to fp32 |
18,971 | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import copy
import json
import math
import logging
import tarfile
import tempfile
import shutil
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from data_utils.file_utils ... | null |
18,972 | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import copy
import json
import math
import logging
import tarfile
import tempfile
import shutil
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from data_utils.file_utils ... | Init method based on N(0, sigma/sqrt(2*num_layers). |
18,973 | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import copy
import json
import math
import logging
import tarfile
import tempfile
import shutil
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from data_utils.file_utils ... | Load tf checkpoints in a pytorch model |
18,974 | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import copy
import json
import math
import logging
import tarfile
import tempfile
import shutil
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from data_utils.file_utils ... | Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) |
18,975 | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import copy
import json
import math
import logging
import tarfile
import tempfile
import shutil
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from data_utils.file_utils ... | null |
18,976 | import copy
import torch
import data_utils
import random
import mpu
from data_utils.wordpiece import BertTokenizer
from torch.utils.data import Subset
def make_data_loader(dataset, batch_size, args):
shuffle = args.shuffle
if shuffle:
#if not args.struct_bert_dataset and not args.palm_dataset:
#... | null |
18,977 | import copy
import torch
import data_utils
import random
import mpu
from data_utils.wordpiece import BertTokenizer
from torch.utils.data import Subset
def make_data_loader(dataset, batch_size, args):
shuffle = args.shuffle
if shuffle:
#if not args.struct_bert_dataset and not args.palm_dataset:
#... | null |
18,978 | import copy
import torch
import data_utils
import random
import mpu
from data_utils.wordpiece import BertTokenizer
from torch.utils.data import Subset
def make_data_loader(dataset, batch_size, args):
shuffle = args.shuffle
if shuffle:
#if not args.struct_bert_dataset and not args.palm_dataset:
#... | null |
18,979 | import copy
import torch
import data_utils
import random
import mpu
from data_utils.wordpiece import BertTokenizer
from torch.utils.data import Subset
def make_data_loader(dataset, batch_size, args):
shuffle = args.shuffle
if shuffle:
#if not args.struct_bert_dataset and not args.palm_dataset:
#... | makes training/val/test |
18,980 | import torch
def calc_mean_invstddev(feature):
def apply_mv_norm(features):
# If there is less than 2 spectrograms, the variance cannot be computed (is NaN)
# and normalization is not possible, so return the item as it is
if features.size(0) < 2:
return features
mean, invstddev = calc_mean_invs... | null |
18,981 | import torch
The provided code snippet includes necessary dependencies for implementing the `lengths_to_encoder_padding_mask` function. Write a Python function `def lengths_to_encoder_padding_mask(lengths, batch_first=False)` to solve the following problem:
convert lengths (a 1-D Long/Int tensor) to 2-D binary tensor ... | convert lengths (a 1-D Long/Int tensor) to 2-D binary tensor Args: lengths: a (B, )-shaped tensor Return: max_length: maximum length of B sequences encoder_padding_mask: a (max_length, B) binary mask, where [t, b] = 0 for t < lengths[b] and 1 otherwise TODO: kernelize this function if benchmarking shows this function i... |
18,982 | import torch
The provided code snippet includes necessary dependencies for implementing the `encoder_padding_mask_to_lengths` function. Write a Python function `def encoder_padding_mask_to_lengths( encoder_padding_mask, max_lengths, batch_size, device )` to solve the following problem:
convert encoder_padding_mask... | convert encoder_padding_mask (2-D binary tensor) to a 1-D tensor Conventionally, encoder output contains a encoder_padding_mask, which is a 2-D mask in a shape (T, B), whose (t, b) element indicate whether encoder_out[t, b] is a valid output (=0) or not (=1). Occasionally, we need to convert this mask tensor to a 1-D t... |
18,983 | def replabel_symbol(i):
"""
Replabel symbols used in wav2letter, currently just "1", "2", ...
This prevents training with numeral tokens, so this might change in the future
"""
return str(i)
The provided code snippet includes necessary dependencies for implementing the `pack_replabels` function. Wr... | Pack a token sequence so that repeated symbols are replaced by replabels |
18,984 | def replabel_symbol(i):
"""
Replabel symbols used in wav2letter, currently just "1", "2", ...
This prevents training with numeral tokens, so this might change in the future
"""
return str(i)
The provided code snippet includes necessary dependencies for implementing the `unpack_replabels` function. ... | Unpack a token sequence so that replabels are replaced by repeated symbols |
18,985 | import json
import os
import re
import torch
from fairseq.data import Dictionary
from fairseq.tasks import FairseqTask, register_task
from examples.speech_recognition.data import AsrDataset
from examples.speech_recognition.data.replabels import replabel_symbol
The provided code snippet includes necessary dependencies ... | Parse data json and create dataset. See scripts/asr_prep_json.py which pack json from raw files Json example: { "utts": { "4771-29403-0025": { "input": { "length_ms": 170, "path": "/tmp/file1.flac" }, "output": { "text": "HELLO \n", "token": "HE LLO", "tokenid": "4815, 861" } }, "1564-142299-0096": { ... } } |
18,986 | import logging
import math
from itertools import groupby
import torch
import torch.nn.functional as F
from fairseq import utils
from fairseq.criterions import FairseqCriterion, register_criterion
from examples.speech_recognition.data.data_utils import encoder_padding_mask_to_lengths
from examples.speech_recognition.uti... | Computes utterance error rate for CTC outputs Args: logprobs: (Torch.tensor) N, T1, D tensor of log probabilities out of the encoder targets: (Torch.tensor) N, T2 tensor of targets input_lengths: (Torch.tensor) lengths of inputs for each sample target_lengths: (Torch.tensor) lengths of targets for each sample blank_idx... |
18,987 | import logging
import math
import os
import sentencepiece as spm
import torch
from fairseq import checkpoint_utils, options, utils, tasks
from fairseq.logging import meters, progress_bar
from fairseq.utils import import_user_module
def check_args(args):
assert args.path is not None, "--path required for generation... | null |
18,988 | import logging
import math
import os
import sentencepiece as spm
import torch
from fairseq import checkpoint_utils, options, utils, tasks
from fairseq.logging import meters, progress_bar
from fairseq.utils import import_user_module
def get_dataset_itr(args, task):
return task.get_batch_iterator(
dataset=ta... | null |
18,989 | import logging
import math
import os
import sentencepiece as spm
import torch
from fairseq import checkpoint_utils, options, utils, tasks
from fairseq.logging import meters, progress_bar
from fairseq.utils import import_user_module
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def process_predicti... | null |
18,990 | import logging
import math
import os
import sentencepiece as spm
import torch
from fairseq import checkpoint_utils, options, utils, tasks
from fairseq.logging import meters, progress_bar
from fairseq.utils import import_user_module
def prepare_result_files(args):
def get_res_file(file_prefix):
path = os.pa... | null |
18,991 | import logging
import math
import os
import sentencepiece as spm
import torch
from fairseq import checkpoint_utils, options, utils, tasks
from fairseq.logging import meters, progress_bar
from fairseq.utils import import_user_module
def load_models_and_criterions(filenames, arg_overrides=None, task=None):
models = ... | null |
18,992 | import logging
import math
import os
import sentencepiece as spm
import torch
from fairseq import checkpoint_utils, options, utils, tasks
from fairseq.logging import meters, progress_bar
from fairseq.utils import import_user_module
The provided code snippet includes necessary dependencies for implementing the `optimiz... | Optimize ensemble for generation |
18,993 | import logging
import math
import os
import sentencepiece as spm
import torch
from fairseq import checkpoint_utils, options, utils, tasks
from fairseq.logging import meters, progress_bar
from fairseq.utils import import_user_module
def add_asr_eval_argument(parser):
parser.add_argument("--kspmodel", default=None, h... | null |
18,994 | from __future__ import absolute_import, division, print_function, unicode_literals
from collections import namedtuple
import concurrent.futures
from itertools import chain
import argparse
import os
import json
import sentencepiece as spm
import multiprocessing
from fairseq.data import Dictionary
MILLISECONDS_TO_SECONDS... | null |
18,995 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | null |
18,996 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | null |
18,997 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | null |
18,998 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | Linear layer (input: N x T x C) |
18,999 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | Weight-normalized Conv1d layer optimized for decoding |
19,000 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | null |
19,001 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | null |
19,002 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | null |
19,003 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | null |
19,004 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | null |
19,005 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | null |
19,006 | import argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
fr... | null |
19,007 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.models import (
FairseqEncoder,
FairseqEncoderModel,
register_model,
register_model_architecture,
)
default_conv_enc_config = """[
(400, 13, 170, 0.2),
(440, 14, 0, 0.214),
(484, 15, 0, 0.22898),
... | null |
19,008 | from __future__ import absolute_import, division, print_function, unicode_literals
import re
from collections import deque
from enum import Enum
import numpy as np
def coordinate_to_offset(row, col, ncols):
return int(row * ncols + col) | null |
19,009 | from __future__ import absolute_import, division, print_function, unicode_literals
import re
from collections import deque
from enum import Enum
import numpy as np
def offset_to_row(offset, ncols):
return int(offset / ncols) | null |
19,010 | from __future__ import absolute_import, division, print_function, unicode_literals
import re
from collections import deque
from enum import Enum
import numpy as np
def offset_to_col(offset, ncols):
return int(offset % ncols) | null |
19,011 | from __future__ import absolute_import, division, print_function, unicode_literals
import re
from collections import deque
from enum import Enum
import numpy as np
class WERTransformer(object):
def __init__(self, hyp_str, ref_str, verbose=True):
self.ed_ = EditDistance(False)
self.id2oracle_errs_ = ... | null |
19,012 | from __future__ import absolute_import, division, print_function, unicode_literals
import re
from collections import deque
from enum import Enum
import numpy as np
class WERTransformer(object):
def __init__(self, hyp_str, ref_str, verbose=True):
self.ed_ = EditDistance(False)
self.id2oracle_errs_ = ... | null |
19,013 | from __future__ import absolute_import, division, print_function, unicode_literals
import re
from collections import deque
from enum import Enum
import numpy as np
def str2toks(str):
pieces = trimWhitespace(str).split(" ")
toks = []
for p in pieces:
toks.append(Token(p, 0.0, 0.0))
return toks
cl... | INPUT: hypothesis string, reference string OUTPUT: List of alignment codes (intermediate results from WER computation) |
19,014 | from __future__ import absolute_import, division, print_function, unicode_literals
import re
from collections import deque
from enum import Enum
import numpy as np
def merge_counts(x, y):
# Merge two hashes which have 'counts' as their values
# This can be used for example to merge confusion pair counts
# ... | null |
19,015 | from functools import lru_cache
import json
def convert_sentence_to_json(sentence):
if '_' in sentence:
prefix, rest = sentence.split('_', 1)
query, rest = rest.split('_', 1)
query_index = len(prefix.rstrip().split(' '))
else:
query, query_index = None, None
prefix, rest = ... | null |
19,016 | from functools import lru_cache
import json
def extended_noun_chunks(sentence):
noun_chunks = {(np.start, np.end) for np in sentence.noun_chunks}
np_start, cur_np = 0, 'NONE'
for i, token in enumerate(sentence):
np_type = token.pos_ if token.pos_ in {'NOUN', 'PROPN'} else 'NONE'
if np_type ... | null |
19,017 | from functools import lru_cache
import json
def find_token(sentence, start_pos):
def find_span(sentence, search_text, start=0):
def get_detokenizer():
def get_spacy_nlp():
def jsonl_iterator(input_fname, positive_only=False, ngram_order=3, eval=False):
detok = get_detokenizer()
nlp = get_spacy_nlp()
with ... | null |
19,018 | from functools import lru_cache
import json
def winogrande_jsonl_iterator(input_fname, eval=False):
with open(input_fname) as fin:
for line in fin:
sample = json.loads(line.strip())
sentence, option1, option2 = sample['sentence'], sample['option1'],\
sample['option2'... | null |
19,019 | from functools import lru_cache
import json
def filter_noun_chunks(chunks, exclude_pronouns=False, exclude_query=None, exact_match=False):
if exclude_pronouns:
chunks = [
np for np in chunks if (
np.lemma_ != '-PRON-'
and not all(tok.pos_ == 'PRON' for tok in np)... | null |
19,020 | import argparse
import json
import os
import re
class InputExample:
def __init__(self, paragraph, qa_list, label):
self.paragraph = paragraph
self.qa_list = qa_list
self.label = label
The provided code snippet includes necessary dependencies for implementing the `get_examples` function. Wri... | Extract paragraph and question-answer list from each json file |
19,021 | import argparse
from itertools import chain
import sys
import random
import numpy as np
from sacrebleu import compute_bleu, corpus_bleu as _corpus_bleu
def dictolist(d):
a = sorted(d.items(), key=lambda i: i[0])
return [i[1] for i in a]
def load_sys(paths):
src, tgt, hypos, log_probs = {}, {}, {}, {}
f... | null |
19,022 | import argparse
from itertools import chain
import sys
import random
import numpy as np
from sacrebleu import compute_bleu, corpus_bleu as _corpus_bleu
def load_ref(path):
with open(path) as f:
lines = f.readlines()
src, tgt, refs = [], [], []
i = 0
while i < len(lines):
if lines[i].sta... | null |
19,023 | import argparse
from itertools import chain
import sys
import random
import numpy as np
from sacrebleu import compute_bleu, corpus_bleu as _corpus_bleu
def merge(src, tgt, hypos, log_probs, path):
with open(path, 'w') as f:
for s, t, hs, lps in zip(src, tgt, hypos, log_probs):
f.write(s + '\n')... | null |
19,024 | import argparse
from itertools import chain
import sys
import random
import numpy as np
from sacrebleu import compute_bleu, corpus_bleu as _corpus_bleu
def corpus_bleu(sys_stream, ref_streams):
bleu = _corpus_bleu(sys_stream, ref_streams, tokenize='none')
return bleu.score
def sentence_bleu(hypothesis, referenc... | null |
19,025 | import argparse
from itertools import chain
import sys
import random
import numpy as np
from sacrebleu import compute_bleu, corpus_bleu as _corpus_bleu
def corpus_bleu(sys_stream, ref_streams):
def pairwise(sents):
def intra_ref(refs):
print('ref pairwise BLEU: %.2f' % pairwise(refs))
refs = list(zip(*refs))
... | null |
19,026 | from contextlib import redirect_stdout
import math
import os
import re
import subprocess
from fairseq import options
from fairseq_cli import eval_lm, preprocess
The provided code snippet includes necessary dependencies for implementing the `reprocess` function. Write a Python function `def reprocess(fle)` to solve the... | reprocess generate.py output |
19,027 | from contextlib import redirect_stdout
import math
import os
import re
import subprocess
from fairseq import options
from fairseq_cli import eval_lm, preprocess
The provided code snippet includes necessary dependencies for implementing the `reprocess_nbest` function. Write a Python function `def reprocess_nbest(fle)` ... | reprocess interactive.py output |
19,028 | from contextlib import redirect_stdout
import math
import os
import re
import subprocess
from fairseq import options
from fairseq_cli import eval_lm, preprocess
def remove_bpe(line, bpe_symbol):
line = line.replace("\n", '')
line = (line + ' ').replace(bpe_symbol, '').rstrip()
return line+("\n")
def remove... | null |
19,029 | from contextlib import redirect_stdout
import math
import os
import re
import subprocess
from fairseq import options
from fairseq_cli import eval_lm, preprocess
def calc_length_from_frac(bpe_sentence, prefix_frac, bpe_symbol):
# return number of words, (not bpe tokens) that we want
no_bpe_sen = remove_bpe(bpe_s... | null |
19,030 | from contextlib import redirect_stdout
import math
import os
import re
import subprocess
from fairseq import options
from fairseq_cli import eval_lm, preprocess
def calc_length_from_frac(bpe_sentence, prefix_frac, bpe_symbol):
# return number of words, (not bpe tokens) that we want
no_bpe_sen = remove_bpe(bpe_s... | parse output of eval_lm |
19,031 | from contextlib import redirect_stdout
import os
from fairseq import options
from fairseq_cli import generate
from . import rerank_options, rerank_utils
def score_bw(args):
if args.backwards1:
scorer1_src = args.target_lang
scorer1_tgt = args.source_lang
else:
scorer1... | null |
19,032 | import math
from multiprocessing import Pool
import numpy as np
from fairseq import bleu, options
from fairseq.data import dictionary
from . import (
rerank_generate,
rerank_score_bw,
rerank_score_lm,
rerank_options,
rerank_utils,
)
def rerank(args):
if type(args.lenpen) is not list:
arg... | null |
19,033 | import argparse
import random
import numpy as np
from fairseq import options
from . import rerank, rerank_options
def random_search(args):
param_values = []
tuneable_parameters = ['lenpen', 'weight1', 'weight2', 'weight3']
initial_params = [args.lenpen, args.weight1, args.weight2, args.weight3]
for i, e... | null |
19,034 | import os
from fairseq import options
from . import rerank_options, rerank_utils
def score_lm(args):
using_nbest = args.nbest_list is not None
pre_gen, left_to_right_preprocessed_dir, right_to_left_preprocessed_dir, \
backwards_preprocessed_dir, lm_preprocessed_dir = \
rerank_utils.get_directori... | null |
19,035 | from contextlib import redirect_stdout
import os
import subprocess
from fairseq import options
from fairseq_cli import generate, preprocess
from . import rerank_options, rerank_utils
def gen_and_reprocess_nbest(args):
if args.score_dict_dir is None:
args.score_dict_dir = args.data
if args.prefix_len is ... | null |
19,036 | import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.models import (
register_model,
register_model_architecture,
)
from fairseq.models.transformer import (
TransformerModel,
TransformerEncoder,
TransformerDecoder,
base_architecture,
transformer_iwslt_de_en,
tr... | null |
19,037 | import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.models import (
register_model,
register_model_architecture,
)
from fairseq.models.transformer import (
TransformerModel,
TransformerEncoder,
TransformerDecoder,
base_architecture,
transformer_iwslt_de_en,
tr... | null |
19,038 | import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.models import (
register_model,
register_model_architecture,
)
from fairseq.models.transformer import (
TransformerModel,
TransformerEncoder,
TransformerDecoder,
base_architecture,
transformer_iwslt_de_en,
tr... | null |
19,039 | import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.models import (
register_model,
register_model_architecture,
)
from fairseq.models.transformer import (
TransformerModel,
TransformerEncoder,
TransformerDecoder,
base_architecture,
transformer_iwslt_de_en,
tr... | null |
19,040 | import torch
def safe_cumprod(tensor, dim: int, eps: float = 1e-10):
"""
An implementation of cumprod to prevent precision issue.
cumprod(x)
= [x1, x1x2, x1x2x3, ....]
= [exp(log(x1)), exp(log(x1) + log(x2)), exp(log(x1) + log(x2) + log(x3)), ...]
= exp(cumsum(log(x)))
"""
if (tensor + e... | Implementing exclusive cumprod. There is cumprod in pytorch, however there is no exclusive mode. cumprod(x) = [x1, x1x2, x2x3x4, ..., prod_{i=1}^n x_i] exclusive means cumprod(x) = [1, x1, x1x2, x1x2x3, ..., prod_{i=1}^{n-1} x_i] |
19,041 | import torch
The provided code snippet includes necessary dependencies for implementing the `lengths_to_mask` function. Write a Python function `def lengths_to_mask(lengths, max_len: int, dim: int = 0, negative_mask: bool = False)` to solve the following problem:
Convert a tensor of lengths to mask For example, length... | Convert a tensor of lengths to mask For example, lengths = [[2, 3, 4]], max_len = 5 mask = [[1, 1, 1], [1, 1, 1], [0, 1, 1], [0, 0, 1], [0, 0, 0]] |
19,042 | import torch
The provided code snippet includes necessary dependencies for implementing the `moving_sum` function. Write a Python function `def moving_sum(x, start_idx: int, end_idx: int)` to solve the following problem:
From MONOTONIC CHUNKWISE ATTENTION https://arxiv.org/pdf/1712.05382.pdf Equation (18) x = [x_1, x_... | From MONOTONIC CHUNKWISE ATTENTION https://arxiv.org/pdf/1712.05382.pdf Equation (18) x = [x_1, x_2, ..., x_N] MovingSum(x, start_idx, end_idx)_n = Sigma_{m=n−(start_idx−1)}^{n+end_idx-1} x_m for n in {1, 2, 3, ..., N} x : src_len, batch_size start_idx : start idx end_idx : end idx Example src_len = 5 batch_size = 3 x ... |
19,043 | import argparse
import sys
import json
from tornado import web, ioloop
from scorers import build_scorer
DEFAULT_HOSTNAME = 'localhost'
DEFAULT_PORT = 12321
def add_args():
parser = argparse.ArgumentParser()
# fmt: off
parser.add_argument('--hostname', type=str, default=DEFAULT_HOSTNAME,
... | null |
19,044 | import argparse
import sys
import json
from tornado import web, ioloop
from scorers import build_scorer
DEFAULT_HOSTNAME = 'localhost'
DEFAULT_PORT = 12321
class EvalSessionHandler(ScorerHandler):
def post(self):
self.scorer.reset()
def get(self):
r = json.dumps(self.scorer.get_info())
s... | null |
19,045 | import argparse
from client import SimulSTEvaluationService, SimulSTLocalEvaluationService
from fairseq.registry import REGISTRIES
from agents import build_agent
DEFAULT_HOSTNAME = 'localhost'
DEFAULT_PORT = 12321
REGISTRIES = {}
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--hostn... | null |
19,046 | import argparse
import fileinput
import hashlib
from multiprocessing import Pool
import sys
def get_hashes_and_lines(raw_line):
hash = hashlib.md5(raw_line).hexdigest()
return hash, raw_line | null |
19,047 | import os.path as op
import argparse
import os
from multiprocessing import cpu_count
from collections import namedtuple
from typing import Optional, List
import sentencepiece as sp
from fairseq.data.encoders.moses_tokenizer import MosesTokenizer
from fairseq.data.encoders.byte_utils import byte_encode
from fairseq.data... | null |
19,048 | import torch.nn as nn
import torch.nn.functional as F
from fairseq.models import register_model, register_model_architecture
from fairseq.models.transformer import TransformerModel, TransformerEncoder
def gru_transformer_base_architecture(args):
args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
... | null |
19,049 | import argparse
import glob
import os
import soundfile
import random
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('root', metavar='DIR', help='root directory containing flac files to index')
parser.add_argument('--valid-percent', default=0.01, type=float, metavar='D',
... | null |
19,050 | import argparse
import glob
import os
from shutil import copy
import h5py
import soundfile as sf
import numpy as np
import torch
from torch import nn
import tqdm
from fairseq.models.wav2vec import Wav2VecModel
The provided code snippet includes necessary dependencies for implementing the `read_audio` function. Write a... | Load an audio file and return PCM along with the sample rate |
19,051 | import torch
class ScalarBias(torch.autograd.Function):
"""
Adds a vector of scalars, used in self-attention mechanism to allow
the model to optionally attend to this vector instead of the past
"""
def forward(ctx, input, dim, bias_init):
size = list(input.size())
size[dim] += 1
... | null |
19,052 | import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `unfold1d` function. Write a Python function `def unfold1d(x, kernel_size, padding_l, pad_value=0)` to solve the following problem:
unfold T x B x C to T x B x C x K
Here is the function:
def unfold1d(x, ke... | unfold T x B x C to T x B x C x K |
19,053 | from typing import Dict, List, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.modules import LayerNorm, MultiheadAttention
from fairseq.modules.quant_noise import quant_noise
from torch import Tensor
def Linear(in_features, out_features, bias=True):
... | null |
19,054 | import numpy as np
import torch
import torch.nn as nn
def logsumexp(x, dim=1):
return torch.logsumexp(x.float(), dim=dim).type_as(x) | null |
19,055 |
def gen_forward():
kernels = [3, 5, 7, 15, 31, 63, 127, 255]
seqs = [32 * x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]
head = """
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the ro... | null |
19,056 |
def gen_backward():
head = """
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "lightconv_cuda.cuh"
std::vector<at::Tensor> lightconv_cuda_backward(
at::... | null |
19,057 |
def gen_forward():
kernels = [3, 5, 7, 15, 31, 63, 127, 255]
blocks = [32, 64, 128, 256]
head = """
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "dyna... | null |
19,058 |
def gen_backward():
kernels = [3, 5, 7, 15, 31, 63, 127, 255]
thresh = [512, 512, 512, 512, 512, 380, 256, 256]
min_block = [64, 64, 64, 64, 64, 64, 128, 256]
seqs = [32 * x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]
head = """
/**
* Copyright (c) Facebook, Inc. and its a... | null |
19,059 | import torch
import torch.nn as nn
import torch.nn.functional as F
try:
from apex.normalization import FusedLayerNorm as _FusedLayerNorm
has_fused_layernorm = True
class FusedLayerNorm(_FusedLayerNorm):
def forward(self, x):
if not x.is_cuda:
return super().forward(x)
... | null |
19,060 | import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.modules.unfold import unfold1d
from fairseq.incremental_decoding_utils import with_incremental_state
class LightweightConv1dTBC(nn.Module):
'''Lightweight Convolution assuming the input is TxBxC
Args:
... | null |
19,061 | import logging
import torch
import torch.nn.functional as F
def _cross_entropy_pytorch(logits, target, ignore_index=None, reduction='mean'):
lprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32)
return F.nll_loss(
lprobs, target, ignore_index=ignore_index, reduction=reduction,
)
def cross_ent... | null |
19,062 | import logging
import torch
import torch.nn.functional as F
def _cross_entropy_pytorch(logits, target, ignore_index=None, reduction='mean'):
lprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32)
return F.nll_loss(
lprobs, target, ignore_index=ignore_index, reduction=reduction,
)
def cross_ent... | null |
19,063 | import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from .unfold import unfold1d
from fairseq.incremental_decoding_utils import with_incremental_state
class DynamicConv1dTBC(nn.Module):
'''Dynamic lightweight convolution taking T x B x C inputs
Args:
input_size: ... | null |
19,064 | import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from .unfold import unfold1d
from fairseq.incremental_decoding_utils import with_incremental_state
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform... | null |
19,065 | from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.modules import (
LayerDropModuleList,
LayerNorm,
MultiheadAttention,
PositionalEmbedding,
TransformerSentenceEncoderLayer,
)
from fairseq.modules.quant_noise import quant_noise as apply... | Initialize the weights specific to the BERT Model. This overrides the default initializations depending on the specified arguments. 1. If normal_init_linear_weights is set then weights of linear layer will be initialized using the normal distribution and bais will be set to the specified value. 2. If normal_init_embed_... |
19,066 | from __future__ import absolute_import, division, print_function, unicode_literals
from collections.abc import Iterable
from itertools import repeat
import torch
import torch.nn as nn
def _pair(v):
if isinstance(v, Iterable):
assert len(v) == 2, "len(v) != 2"
return v
return tuple(repeat(v, 2)) | null |
19,067 | from __future__ import absolute_import, division, print_function, unicode_literals
from collections.abc import Iterable
from itertools import repeat
import torch
import torch.nn as nn
def infer_conv_output_dim(conv_op, input_dim, sample_inchannel):
sample_seq_len = 200
sample_bsz = 10
x = torch.randn(sampl... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.