code
stringlengths
17
6.64M
def load_converted_model(ckpt: str): ckpt_state = torch.load(ckpt, map_location='cpu') for required_key in ['task_cfg', 'model_cfg', 'model_weight']: if (required_key not in ckpt_state): raise ValueError(f'{ckpt} is not a valid checkpoint since the required key: {required_key} is missing')...
class UpstreamExpert(UpstreamBase): def __init__(self, ckpt, **kwargs): super().__init__(**kwargs) (self.model, task_cfg) = load_converted_model(ckpt) if (len(self.hooks) == 0): self.add_hook('self.model.feature_extractor', (lambda input, output: output.transpose(1, 2))) ...
class LegacyUpstreamExpert(UpstreamBase): def __init__(self, ckpt, **kwargs): super().__init__(**kwargs) logger.warning('Use the legacy expert for HuBERT which depends on fairseq') import fairseq from fairseq.models.wav2vec import Wav2VecModel from packaging import version...
def base_wav2vec_architecture(args): conv_feature_layers = '[(512, 10, 5)]' conv_feature_layers += ' + [(512, 8, 4)]' conv_feature_layers += ' + [(512, 4, 2)] * 3' args.conv_feature_layers = getattr(args, 'conv_feature_layers', conv_feature_layers) args.conv_aggregator_layers = getattr(args, 'conv...
def wav2vec_custom(ckpt: str, *args, legacy: bool=False, refresh: bool=False, **kwargs): if ckpt.startswith('http'): ckpt = _urls_to_filepaths(ckpt, refresh=refresh)
def wav2vec_local(*args, **kwargs): return wav2vec_custom(*args, **kwargs)
def wav2vec_url(*args, **kwargs): return wav2vec_custom(*args, **kwargs)
def wav2vec(refresh=False, *args, **kwargs): '\n The default model - Large model\n refresh (bool): whether to download ckpt/config again if existed\n ' return wav2vec_large(*args, refresh=refresh, **kwargs)
def wav2vec_large(refresh=False, legacy=False, **kwargs): '\n The Large model\n refresh (bool): whether to download ckpt/config again if existed\n ' kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/wav2vec/wav2vec_large.pt' if (not legacy): kwargs['ckpt'] = 'https://huggingfac...
def load_and_convert_fairseq_ckpt(fairseq_source: str, output_path: str=None): (state, cfg) = load_fairseq_ckpt(fairseq_source) output_state = {'task_cfg': cfg['task'], 'model_cfg': cfg['model'], 'model_weight': state['model']} if (output_path is not None): Path(output_path).parent.mkdir(exist_ok=...
def load_converted_model(ckpt: str): ckpt_state = torch.load(ckpt, map_location='cpu') for required_key in ['task_cfg', 'model_cfg', 'model_weight']: if (required_key not in ckpt_state): raise ValueError(f'{ckpt} is not a valid checkpoint since the required key: {required_key} is missing')...
def wav2vec2_custom(ckpt: str, legacy: bool=False, fairseq: bool=False, refresh: bool=False, **kwargs): assert (not (legacy and fairseq)), "The option 'legacy' will directly load a fairseq checkpoint, while the option 'fairseq' will first convert the fairseq checkpoint to be fairseq indenpendent and then load the...
def wav2vec2_local(*args, **kwargs): return wav2vec2_custom(*args, **kwargs)
def wav2vec2_url(*args, **kwargs): return wav2vec2_custom(*args, **kwargs)
def wav2vec2(refresh=False, *args, **kwargs): '\n The default model - Base\n refresh (bool): whether to download ckpt/config again if existed\n ' return wav2vec2_base_960(*args, refresh=refresh, **kwargs)
def wav2vec2_base_960(refresh=False, legacy=False, **kwargs): '\n The Base model\n refresh (bool): whether to download ckpt/config again if existed\n ' kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/wav2vec/wav2vec_small.pt' if (not legacy): kwargs['ckpt'] = 'https://hugging...
def wav2vec2_large_960(refresh=False, legacy=False, **kwargs): '\n The Large model trained on LibriSpeech 960 hours of data\n refresh (bool): whether to download ckpt/config again if existed\n ' kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/wav2vec/libri960_big.pt' if (not legacy):...
def wav2vec2_large_ll60k(refresh=False, legacy=False, **kwargs): '\n The Large model trained on Libri-light 60k hours of data\n refresh (bool): whether to download ckpt/config again if existed\n ' kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/wav2vec/wav2vec_vox_new.pt' if (not leg...
def wav2vec2_large_lv60_cv_swbd_fsh(refresh=False, legacy=False, **kwargs): '\n The Large model trained on Libri-Light 60k hours + CommonVoice + Switchboard + Fisher\n refresh (bool): whether to download ckpt/config again if existed\n ' kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/wav...
def xlsr_53(refresh=False, legacy=False, **kwargs): '\n The wav2vec 2.0 model trained on multilingual presented in https://arxiv.org/abs/2006.13979\n refresh (bool): whether to download ckpt/config again if existed\n ' kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/wav2vec/xlsr_53_56k.p...
def xls_r_300m(refresh=False, legacy=False, **kwargs): '\n XLS-R, this smallest size has the same parameters as the Largs model of wav2vec 2.0 and HuBERT\n ' kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/wav2vec/xlsr2_300m.pt' if (not legacy): kwargs['ckpt'] = 'https://huggingface...
def xls_r_1b(refresh=False, legacy=False, **kwargs): kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/wav2vec/xlsr2_960m_1000k.pt' if (not legacy): kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/xlsr2_960m_1000k.pt' return wav2vec2_custom(refresh=refresh, legac...
def xls_r_2b(refresh=False, legacy=False, **kwargs): kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/wav2vec/xlsr2_2B_1000k.pt' if (not legacy): kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/xlsr2_2B_1000k.pt' return wav2vec2_custom(refresh=refresh, legacy=le...
def wav2vec2_conformer_relpos(refresh=False, legacy=False, **kwargs): kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/conformer/wav2vec2/librilight/LL_relpos_PT_no_FT' if (not legacy): kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/LL_relpos_PT_no_FT.pt' retur...
def wav2vec2_conformer_rope(refresh=False, legacy=False, **kwargs): kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/conformer/wav2vec2/librilight/LL_rope_PT_no_FT' if (not legacy): kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/LL_rope_PT_no_FT.pt' return wav2...
def wav2vec2_large_voxpopuli_100k(refresh=False, legacy=False, **kwargs): kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/voxpopuli/models/wav2vec2_large_100k.pt' if (not legacy): kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/wav2vec2_large_100k.pt' return wav2vec2_c...
def wav2vec2_base_s2st_es_voxpopuli(refresh=False, legacy=False, **kwargs): kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/speech_to_speech/s2st_finetuning/w2v2/es/transformer_B.pt' if (not legacy): kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/wav2vec2_base_s2s...
def wav2vec2_conformer_large_s2st_es_voxpopuli(refresh=False, legacy=False, **kwargs): kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/speech_to_speech/s2st_finetuning/w2v2/es/conformer_L.pt' if (not legacy): kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/wav2vec2...
def wav2vec2_base_s2st_en_librilight(refresh=False, legacy=False, **kwargs): kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/fairseq/speech_to_speech/s2st_finetuning/w2v2/en/transformer_B.pt' if (not legacy): kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/wav2vec2_base_s2...
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...