code stringlengths 17 6.64M |
|---|
def wav2vec2_conformer_large_s2st_en_librilight(refresh=False, legacy=False, **kwargs):
kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/speech_to_speech/s2st_finetuning/w2v2/en/conformer_L.pt'
if (not legacy):
kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/wav2vec... |
class UpstreamExpert(UpstreamBase):
def __init__(self, ckpt, **kwargs):
super().__init__(**kwargs)
checkpoint = torch.load(ckpt)
self.cfg = WavLMConfig(checkpoint['cfg'])
self.model = WavLM(self.cfg)
self.model.load_state_dict(checkpoint['model'])
self.model.featur... |
def wavlm_local(ckpt, *args, **kwargs):
'\n The model from local ckpt\n ckpt (str): PATH\n '
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def wavlm_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from google drive id\n ckpt (str): URL\n refresh (bool): whether to download ckpt/config again if existed\n '
return wavlm_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
|
def wavlm(refresh=False, *args, **kwargs):
'\n The default model - Base-Plus\n refresh (bool): whether to download ckpt/config again if existed\n '
return wavlm_base_plus(*args, refresh=refresh, **kwargs)
|
def wavlm_base(refresh=False, *args, **kwargs):
'\n The Base model\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/wavlm_base.pt'
return wavlm_url(*args, refresh=refresh, **kwargs)
|
def wavlm_base_plus(refresh=False, *args, **kwargs):
'\n The Base-Plus model\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/wavlm_base_plus.pt'
return wavlm_url(*args, refresh=refresh, **kwargs... |
def wavlm_large(refresh=False, *args, **kwargs):
'\n The Large model\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/wavlm_large.pt'
return wavlm_url(*args, refresh=refresh, **kwargs)
|
def get_cache_dir():
_default_cache_dir.mkdir(exist_ok=True, parents=True)
return _default_cache_dir
|
def set_cache_dir(cache_dir: str):
global _default_cache_dir
_default_cache_dir = Path(cache_dir)
|
def get_audio_info(audio_paths: List[str], audio_ids: List[str], cache_dir: str=None, num_workers: int=6) -> List[dict]:
'\n Use :code:`torchaudio.info` to retrieve the metadata from audio paths.\n The retrieved metadata is cached in :code:`cache_dir`\n '
cache_dir = (cache_dir or get_cache_dir())
... |
class benchmark(ContextDecorator):
def __init__(self, name: str, freq: int=1) -> None:
super().__init__()
self.name = name
self.freq = freq
def __enter__(self):
torch.cuda.synchronize()
self.start = time()
def __exit__(self, exc_type: Any, exc_value: Any, traceba... |
def get_dir():
_download_dir.mkdir(exist_ok=True, parents=True)
return _download_dir
|
def set_dir(d):
global _download_dir
_download_dir = Path(d)
|
def _download_url_to_file(url, dst, hash_prefix=None, progress=True):
'\n This function is not thread-safe. Please ensure only a single\n thread or process can enter this block at the same time\n '
file_size = None
req = Request(url, headers={'User-Agent': 'torch.hub'})
u = urlopen(req)
m... |
def _download_url_to_file_requests(url, dst, hash_prefix=None, progress=True):
'\n Alternative download when urllib.Request fails.\n '
req = requests.get(url, stream=True, headers={'User-Agent': 'torch.hub'})
file_size = int(req.headers['Content-Length'])
dst = os.path.expanduser(dst)
dst_di... |
def _download(filepath: Path, url, refresh: bool, new_enough_secs: float=2.0):
'\n If refresh is True, check the latest modfieid time of the filepath.\n If the file is new enough (no older than `new_enough_secs`), than directly use it.\n If the file is older than `new_enough_secs`, than re-download the f... |
def _urls_to_filepaths(*args, refresh=False, download: bool=True):
'\n Preprocess the URL specified in *args into local file paths after downloading\n\n Args:\n Any number of URLs (1 ~ any)\n\n Return:\n Same number of downloaded file paths\n '
def _url_to_filepath(url):
ass... |
def parse_override(string):
'\n Example usgae:\n -o "optimizer.lr=1.0e-3,,optimizer.name=\'AdamW\',,runner.eval_dataloaders=[\'dev\', \'test\']"\n\n Convert to:\n {\n "optimizer": {"lr": 1.0e-3, "name": "AdamW"},\n "runner": {"eval_dataloaders": ["dev", "test"]}\n ... |
def parse_overrides(options: list):
'\n Example usgae:\n [\n "--optimizer.lr",\n "1.0e-3",\n "--optimizer.name",\n "AdamW",\n "--runner.eval_dataloaders",\n "[\'dev\', \'test\']",\n ]\n\n Convert to:\n {\n "opt... |
class pseudo_audio():
'\n This context manager returns filepaths (List[str]) and num_samples (List[int]) on entering\n '
def __init__(self, secs: List[float], sample_rate: int=SAMPLE_RATE):
self.tempdir = Path(tempfile.TemporaryDirectory().name)
self.tempdir.mkdir(parents=True, exist_ok... |
def get_pseudo_wavs(seed: int=0, n: int=2, min_secs: int=1, max_secs: int=3, sample_rate: int=SAMPLE_RATE, device: str='cpu', padded: bool=False):
random.seed(seed)
torch.manual_seed(seed)
wavs = []
wavs_len = []
for _ in range(n):
wav_length = random.randint((min_secs * sample_rate), (max... |
def fix_random_seeds(seed: int=1337) -> None:
'Fixes all random seeds, including cuDNN backends.\n\n Args:\n seed (int, optional): Random seed. Defaults to 1337.\n '
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_... |
def read_file(path, callback=(lambda x: x), sep=' ', default_value=''):
content = {}
with open(path, 'r') as file:
lines = file.readlines()
for (idx, line) in enumerate(lines):
fields = line.strip().split(sep, maxsplit=1)
if (len(fields) > 1):
(filename,... |
def get_ddp_sampler(dataset: Dataset, epoch: int):
'\n This function will create a DistributedSampler if DDP is initialized,\n and will just return None if DDP is not initialized.\n '
if is_initialized():
sampler = DistributedSampler(dataset)
sampler.set_epoch(epoch)
else:
... |
def _download(filename, url, refresh, agent):
dirpath = f'{torch.hub.get_dir()}/s3prl_cache'
os.makedirs(dirpath, exist_ok=True)
filepath = f'{dirpath}/{filename}'
with FileLock((filepath + '.lock')):
if ((not os.path.isfile(filepath)) or refresh):
if (agent == 'wget'):
... |
def _urls_to_filepaths(*args, refresh=False, agent='wget'):
'\n Preprocess the URL specified in *args into local file paths after downloading\n\n Args:\n Any number of URLs (1 ~ any)\n\n Return:\n Same number of downloaded file paths\n '
def url_to_filename(url):
assert (typ... |
def _gdriveids_to_filepaths(*args, refresh=False):
'\n Preprocess the Google Drive id specified in *args into local file paths after downloading\n\n Args:\n Any number of Google Drive ids (1 ~ any)\n\n Return:\n Same number of downloaded file paths\n '
def gdriveid_to_url(gdriveid):... |
def check_model_equiv(model1, model2):
for (p1, p2) in zip(model1.parameters(), model2.parameters()):
if (p1.data.ne(p2.data).sum() > 0):
return False
if (not torch.equal(p1[0], p2[0])):
return False
if (not torch.equal(p1[1].data, p2[1].data)):
return F... |
def copyParams(module_src, module_dest):
params1 = module_src.named_parameters()
params2 = module_dest.named_parameters()
dict_params2 = dict(params2)
for (name1, param1) in params1:
if (name1 in dict_params2):
dict_params2[name1].data.copy_(param1.data)
|
def main():
input_ckpt = sys.argv[1]
from transformer.nn_transformer import SPEC_TRANSFORMER
options = {'ckpt_file': input_ckpt, 'load_pretrain': 'True', 'no_grad': 'True', 'dropout': 'default', 'spec_aug': 'False', 'spec_aug_prev': 'True', 'weighted_sum': 'False', 'select_layer': (- 1), 'permute_input': ... |
def main():
log_file = str(sys.argv[1])
ckpts = glob.glob((os.path.dirname(log_file) + '/states-*.ckpt'))
sorted_ckpts = sorted(ckpts, key=(lambda ckpt: int(ckpt.split('.')[0].split('-')[(- 1)])))
print(f'The last ckpt: {sorted_ckpts[(- 1)]}')
if (len(sys.argv) == 3):
stop_step = int(sys.a... |
def main():
log_file = str(sys.argv[1])
if (len(sys.argv) == 4):
rank_by = str(sys.argv[2])
target = str(sys.argv[3])
large_or_small = str(sys.argv[4])
else:
rank_by = 'dev'
target = 'test'
large_or_small = '+'
best_record = [(- 99999), 0, None]
if (... |
def compare(a, b, large_or_small):
if (large_or_small == '+'):
return (a > b)
elif (large_or_small == '-'):
return (a < b)
else:
raise ValueError(large_or_small)
|
def is_leader_process():
return ((not is_initialized()) or (get_rank() == 0))
|
def count_parameters(model):
return sum((p.numel() for p in model.parameters() if p.requires_grad))
|
def count_used_parameters(model):
return sum((p.numel() for p in model.parameters() if (p.grad is not None)))
|
def get_time_tag():
return datetime.fromtimestamp(time()).strftime('%Y-%m-%d-%H-%M-%S')
|
def backup(src_path, tgt_dir):
stem = Path(src_path).stem
suffix = Path(src_path).suffix
shutil.copyfile(src_path, os.path.join(tgt_dir, f'{stem}_{get_time_tag()}{suffix}'))
|
def get_model_state(model):
if isinstance(model, DDP):
return model.module.state_dict()
return model.state_dict()
|
def show(*args, **kwargs):
if is_leader_process():
print(*args, **kwargs)
|
def hack_isinstance():
_isinstance = builtins.isinstance
def isinstance(obj, cls):
if _isinstance(obj, defaultdict):
return (_isinstance(obj, cls) and issubclass(cls, defaultdict))
return _isinstance(obj, cls)
builtins.isinstance = isinstance
|
def override(string, args, config):
'\n Example usgae:\n -o "config.optimizer.lr=1.0e-3,,config.optimizer.name=\'AdamW\',,config.runner.eval_dataloaders=[\'dev\', \'test\']"\n '
options = string.split(',,')
for option in options:
option = option.strip()
(key, value_str) = opti... |
def zero_mean_unit_var_norm(input_values: List[np.ndarray]) -> List[np.ndarray]:
'\n Every array in the list is normalized to have zero mean and unit variance\n Taken from huggingface to ensure the same behavior across s3prl and huggingface\n Reference: https://github.com/huggingface/transformers/blob/a2... |
def parse_prune_heads(config):
if (('prune_headids' in config['transformer']) and (config['transformer']['prune_headids'] != 'None')):
heads_int = []
spans = config['transformer']['prune_headids'].split(',')
for span in spans:
endpoints = span.split('-')
if (len(end... |
def get_transformer_tester(from_path='result/result_transformer/libri_sd1337_fmllrBase960-F-N-K-RA/model-1000000.ckpt', display_settings=False):
' Wrapper that loads the transformer model from checkpoint path '
all_states = torch.load(from_path, map_location='cpu')
config = all_states['Settings']['Config'... |
def compute_lnsr(real, adve, norm_L2=True):
real = real.reshape(real.shape[0], (- 1))
adve = adve.reshape(adve.shape[0], (- 1))
l2 = np.linalg.norm((real - adve), ord=2)
if norm_L2:
l2 /= np.linalg.norm(real, ord=2)
return l2
|
def run_over_layer(layer, real_todo, adve_todo):
if (layer != 'feature'):
options = {'ckpt_file': 'result/result_transformer/mockingjay/LinearLarge-libri/model-500000.ckpt', 'load_pretrain': 'True', 'no_grad': 'True', 'dropout': 'default', 'spec_aug': 'False', 'spec_aug_prev': 'True', 'weighted_sum': 'Fal... |
def main():
num_layers = 12
data_path = 'data/adversarial/'
data_type = ['fgsm_8.0', 'fgsm_16.0', 'pgd_8.0', 'pgd_16.0']
data_type = data_type[0]
real_data = os.path.join(data_path, 'original')
adve_data = os.path.join(data_path, data_type)
real_todo = sorted(list(Path(real_data).rglob('*.... |
def get_speaker_from_path(x):
return x.split('/')[(- 1)].split('.')[0].split('-')[0]
|
def get_all_speakers(X):
speaker_set = {}
for x in X:
speaker = get_speaker_from_path(x)
if (speaker not in speaker_set):
speaker_set[speaker] = 0
else:
speaker_set[speaker] += 1
return speaker_set
|
def compute_speaker2idx(speakers):
idx = 0
speaker2idx = {}
for speaker in sorted(speakers):
if ((speaker not in speaker2idx) and (speakers[speaker] > SPEAKER_THRESHOLD)):
speaker2idx[speaker] = idx
idx += 1
return speaker2idx
|
def main():
tables = pd.read_csv(os.path.join(root, ('train-clean-100' + '.csv')))
print('[Dataset] - Computing speaker class...')
O = tables['file_path'].tolist()
speakers = get_all_speakers(O)
speaker2idx = compute_speaker2idx(speakers)
class_num = len(speaker2idx)
print('[Dataset] - Pos... |
def print_cache_path(url: str, refresh: bool):
print(_urls_to_filepaths(url, refresh=refresh))
|
def get_ttest_args():
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mode', choices=['ttest', 'fisher', 'mcnemar'], default='ttest')
parser.add_argument('-em', '--evaluate_metric', default='acc')
parser.add_argument('-t', '--evaluate_split', default='test')
parser.add_argument('-o... |
def get_past_exp(args, past_exp, name):
if os.path.isdir(past_exp):
ckpt_pths = glob.glob(os.path.join(past_exp, f'{name}.ckpt'))
assert (len(ckpt_pths) > 0)
if (len(ckpt_pths) == 1):
ckpt_pth = ckpt_pths[0]
else:
ckpt_pths = sorted(ckpt_pths, key=(lambda pt... |
class Tester(Runner):
'\n Used to handle the evaluation loop and return the testing records for Paired Sample T-test.\n '
def __init__(self, args, config):
super(Tester, self).__init__(args, config)
def evaluate(self):
'evaluate function will always be called on a single process ev... |
def process_records(records, metric):
assert ('sample_wise_metric' in records), 'Utterance-wise / sample-wise metric is necessary for proceeding the Paired Sample T-test.'
average = torch.FloatTensor(records[metric]).mean().item()
return (average, records['sample_wise_metric'])
|
def main():
torch.multiprocessing.set_sharing_strategy('file_system')
torchaudio.set_audio_backend('sox_io')
hack_isinstance()
(mode, args1, config1, args2, config2) = get_ttest_args()
random.seed(args1.seed)
np.random.seed(args1.seed)
torch.manual_seed(args1.seed)
if torch.cuda.is_ava... |
class Timer():
def __init__(self):
self.timings = {}
self.start_time = 0
def start(self):
self.start_time = time.time()
def end(self):
frameinfo = inspect.getouterframes(inspect.currentframe())[1]
filename = frameinfo.filename
filename = '/'.join(filename... |
def get_runner_args():
parser = argparse.ArgumentParser(description='Argument Parser for the S3PLR project.')
parser.add_argument('--config', default='../config/deprecated_runner/tera_libri_fmllrBase_pretrain,yaml', type=str, help='Path to experiment config.', required=False)
parser.add_argument('--seed',... |
def main():
(config, args) = get_runner_args()
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(args.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
if a... |
def pytest_addoption(parser):
parser.addoption('--runupstream', action='store_true', help='run upstream tests')
parser.addoption('--runslow', action='store_true', help='run slow tests')
parser.addoption('--runcorpus', action='store_true', help='run tests with corpus path dependency')
parser.addoption(... |
def pytest_generate_tests(metafunc):
option_value = metafunc.config.option.upstream_names
if ('upstream_names' in metafunc.fixturenames):
metafunc.parametrize('upstream_names', [option_value])
|
def pytest_configure(config):
config.addinivalue_line('markers', 'upstream: mark test as a upstream test case')
config.addinivalue_line('markers', 'slow: mark test as slow to run')
config.addinivalue_line('markers', 'corpus: mark test as required corpus path dependency')
config.addinivalue_line('marke... |
def pytest_collection_modifyitems(config, items):
if (not config.getoption('--runupstream')):
skip_upstream = pytest.mark.skip(reason='need --runupstream option to run')
for item in items:
if ('upstream' in item.keywords):
item.add_marker(skip_upstream)
if (not conf... |
class Helper():
pass
|
@pytest.fixture
def helpers():
return Helper
|
@pytest.mark.parametrize('vocab_type', ['subword', 'character'])
def test_superb_asr(vocab_type):
if (vocab_type == 'subword'):
vocab_args = {'vocab_size': 18}
else:
vocab_args = {}
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, nu... |
def test_superb_er():
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num_samples):
class TestER(SuperbER):
def default_config(self) -> dict:
config = super().default_config()
config['pr... |
def test_superb_ks():
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num_samples):
class TestKS(SuperbKS):
def default_config(self) -> dict:
config = super().default_config()
config['pr... |
def test_superb_pr():
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num_samples):
class TestPR(SuperbPR):
def default_config(self) -> dict:
config = super().default_config()
config['pr... |
def test_superb_ic():
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num_samples):
class TestIC(SuperbIC):
def default_config(self) -> dict:
config = super().default_config()
config['pr... |
def test_superb_sid():
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num_samples):
class TestSID(SuperbSID):
def default_config(self) -> dict:
config = super().default_config()
config[... |
def test_superb_sd():
with tempfile.TemporaryDirectory() as tempdir:
secs = [10, 2, 1, 8, 5]
with pseudo_audio(secs) as (wav_paths, num_samples):
class TestSD(SuperbSD):
def default_config(self) -> dict:
config = super().default_config()
... |
def test_superb_asv():
with tempfile.TemporaryDirectory() as tempdir:
secs = [10, 2, 1, 8, 5]
with pseudo_audio(secs) as (wav_paths, num_samples):
class TestASV(SuperbASV):
def default_config(self) -> dict:
config = super().default_config()
... |
@pytest.mark.parametrize('vocab_type', ['subword', 'character'])
def test_superb_sf(vocab_type):
if (vocab_type == 'subword'):
vocab_args = {'vocab_size': 22}
else:
vocab_args = {}
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num... |
def test_audio_info():
with pseudo_audio([3.0, 4.1, 1.1]) as (paths, num_samples):
infos = get_audio_info(paths, [Path(path).stem for path in paths])
assert (infos[0]['num_frames'] == (3 * 16000))
|
@pytest.mark.parametrize('duplicate', [10000, 100000])
def test_balanced_weighted_sampler(duplicate: int):
labels = ['a', 'a', 'b', 'a']
batch_size = 5
prev_diff_ratio = 1.0
sampler = BalancedWeightedSampler(labels, batch_size=batch_size, duplicate=duplicate, seed=0)
indices = list(sampler)
as... |
@pytest.mark.extra_dependency
def test_beam_decoder():
decoder = BeamDecoder()
emissions = torch.randn((4, 100, 31))
emissions = torch.log_softmax(emissions, dim=2)
hyps = decoder.decode(emissions)
|
def _download_with_timeout(timeout: float, num_process: int):
processes = []
for _ in range(num_process):
process = Process(target=_urls_to_filepaths, args=(URL,), kwargs=dict(refresh=True))
process.start()
processes.append(process)
exitcodes = []
for process in processes:
... |
def test_download():
filepath = Path(_urls_to_filepaths(URL, download=False))
if filepath.is_file():
os.remove(filepath)
logger.info('This should timeout')
_download_with_timeout(0.1, 2)
assert (not filepath.is_file()), 'The download should failed due to the too short timeout second: 0.1 s... |
@pytest.mark.corpus
@pytest.mark.parametrize('fold_id', [0, 1, 2, 3, 4])
def test_er_dataset(fold_id):
v3_er_folder = (((Path(__file__).parent.parent / 's3prl') / 'downstream') / 'emotion')
IEMOCAP = dotenv_values()['IEMOCAP']
with (v3_er_folder / 'config.yaml').open() as file:
config = yaml.load(... |
@pytest.mark.corpus
def test_fluent_commands():
config = dotenv_values()
dataset_root = config['FluentSpeechCommands']
dataset = FluentSpeechCommands(dataset_root)
dataset.data_split_ids
dataset.data_split
dataset.all_data
|
def test_chunking():
chunks = list(chunking(0.0, 8.5, 2.0, 1.0, False))
assert (len(chunks) == 7)
chunks = list(chunking(1.1, 8.5, 2.0, 1.0, True))
assert (len(chunks) == 8)
|
def test_frame_tensor_label():
labels = [(0, 3.0, 4.1), (1, 1.2, 3.2)]
label = chunk_labels_to_frame_tensor_label(1.5, 4.0, labels, 3, 160)
assert (label[((- 1), 0)] == 1)
assert (label[(0, 1)] == 1)
|
def test_g2p():
g2p = G2P()
char_sent = 'HELLO WORLD'
phn_sent = g2p.encode(char_sent)
logging.info(phn_sent)
|
@pytest.mark.corpus
def test_librispeech_dataset():
config = dotenv_values()
dataset_root = config['LibriSpeech']
dataset = LibriSpeech(dataset_root, train_split=['train-clean-100', 'train-clean-360'], valid_split=['dev-clean', 'dev-other'], test_split=['test-clean', 'test-other'])
data = dataset.all_... |
@pytest.mark.corpus
def test_librilight():
config = dotenv_values()
train_corpus = LibriLight(config['LibriLight'])
eval_corpus = LibriSpeech(config['LibriSpeech'], 4, [])
train_data = train_corpus.all_data
(_, valid_data, test_data) = eval_corpus.data_split
assert (len(train_data) == 48)
|
def test_FrameLevel(helpers):
module = FrameLevel(3, 4, [5, 6])
x = torch.randn(32, 10, 3)
x_len = (torch.ones(32) * 3).long()
(h, hl) = module(x, x_len)
|
def test_load_audio():
with pseudo_audio([3.0, 4.0, 5.2]) as (paths, num_frames):
dataset = LoadAudio(paths, [None, 1.0, 3.1], [None, 3.2, None], max_secs=4.2)
for item in dataset:
assert isinstance(item['wav'], torch.Tensor)
|
def isclose(x: float, y: float) -> float:
return (abs((x - y)) < 1e-09)
|
def test_metric():
hyps = ['a ac abb d']
refs = ['a ab abc d']
assert isclose(cer(hyps, refs), 0.2)
assert isclose(wer(hyps, refs), 0.5)
assert isclose(per(hyps, refs), 0.5)
|
@pytest.mark.parametrize('pooling_type', ['MeanPooling', 'TemporalStatisticsPooling', 'AttentiveStatisticsPooling', 'SelfAttentivePooling'])
def test_utterance_level_with_pooling(pooling_type: str):
model = UtteranceLevel(256, 64, [128], 'ReLU', None, pooling_type, None)
output = model(torch.randn(32, 100, 25... |
@pytest.mark.corpus
def test_quesst14_for_qbe():
def quesst14_for_qbe(dataset_root: str):
corpus = Quesst14(dataset_root)
def path_to_dict(path: str):
return dict(wav_path=path)
return dict(all_data={Path(path).stem: path_to_dict(path) for path in ((corpus.valid_queries + cor... |
def test_rnn(helpers):
modules = [RNNEncoder(input_size=8, output_size=6, module='LSTM', hidden_size=[10, 10, 10], dropout=[0.1, 0.1, 0.1], layer_norm=[True, True, True], proj=[True, True, True], sample_rate=[1, 2, 1], sample_style='drop', bidirectional=True), RNNEncoder(input_size=8, output_size=6, module='LSTM'... |
def _merge_batch_indices(batch_indices):
all_indices = []
for indices in batch_indices:
all_indices += indices
return all_indices
|
@pytest.mark.parametrize('world_size', [1, 2, 3, 4, 5, 6, 7, 8])
def test_distributed_sampler(world_size):
sampler = [[1, 2, 3], [4, 5, 6, 7], [8], [9, 10]]
ddp_indices = []
for rank in range(world_size):
ddp_sampler = DistributedBatchSamplerWrapper(sampler, world_size, rank)
ddp_indices +... |
@pytest.mark.parametrize('batch_size', [1, 2, 3, len(data)])
def test_FixedBatchSizeBatchSampler(batch_size):
dataset = data
iter1 = list(iter(FixedBatchSizeBatchSampler(dataset, batch_size, shuffle=False)))
iter2 = list(iter(FixedBatchSizeBatchSampler(dataset, batch_size, shuffle=True)))
indices1 = s... |
@pytest.mark.corpus
def test_snips():
config = dotenv_values()
dataset_root = config['SNIPS']
dataset = SNIPS(dataset_root, ['Ivy', 'Joanna', 'Joey', 'Justin', 'Kendra', 'Kimberly', 'Matthew', 'Salli'], ['Aditi', 'Amy', 'Geraint', 'Nicole'], ['Brian', 'Emma', 'Raveena', 'Russell'])
(train_data, valid_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.