code stringlengths 17 6.64M |
|---|
def get_Adam(model_params, lr=0.0002, **kwargs):
params = []
for m in model_params:
params += list(m.parameters())
return Adam(params, lr=lr, betas=(0.9, 0.999))
|
def get_AdamW(model_params, lr=0.0002, **kwargs):
params = []
for m in model_params:
params += list(m.parameters())
optimizer = AdamW(params, lr=lr)
return optimizer
|
def get_TorchOptim(model_params, torch_optim_name, **kwargs):
params = []
for m in model_params:
params += list(m.parameters())
Opt_class = getattr(torch.optim, torch_optim_name)
kwargs.pop('total_steps')
optim = Opt_class(params, **kwargs)
return optim
|
class AdamW(Optimizer):
"\n Implements Adam algorithm with weight decay fix as introduced in\n `Decoupled Weight Decay Regularization <https://arxiv.org/abs/1711.05101>`__.\n Parameters:\n params (:obj:`Iterable[torch.nn.parameter.Parameter]`):\n Iterable of parameters to optimize or di... |
class _LRSchedule(ABC):
' Parent of all LRSchedules here. '
warn_t_total = False
def __init__(self, warmup=0.002, t_total=(- 1), **kw):
'\n :param warmup: what fraction of t_total steps will be used for linear warmup\n :param t_total: how many training steps (updates) are planned\n... |
class ConstantLR(_LRSchedule):
def get_lr_(self, progress):
return 1.0
|
class WarmupCosineSchedule(_LRSchedule):
'\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n Decreases learning rate from 1. to 0. over remaining `1 - warmup` steps following a cosine curve.\n If `cycles` (default=0.5) is different from default, learning rate foll... |
class WarmupCosineWithHardRestartsSchedule(WarmupCosineSchedule):
'\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n If `cycles` (default=1.) is different from default, learning rate follows `cycles` times a cosine decaying\n learning rate (with hard restarts).\n... |
class WarmupCosineWithWarmupRestartsSchedule(WarmupCosineWithHardRestartsSchedule):
'\n All training progress is divided in `cycles` (default=1.) parts of equal length.\n Every part follows a schedule with the first `warmup` fraction of the training steps linearly increasing from 0. to 1.,\n followed by ... |
class WarmupConstantSchedule(_LRSchedule):
'\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n Keeps learning rate equal to 1. after warmup.\n '
def get_lr_(self, progress):
if (progress < self.warmup):
return (progress / self.warmup)
... |
class WarmupLinearSchedule(_LRSchedule):
'\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n Linearly decreases learning rate from 1. to 0. over remaining `1 - warmup` steps.\n '
warn_t_total = True
def get_lr_(self, progress):
if (progress < self... |
class BertAdam(Optimizer):
"Implements BERT version of Adam algorithm with weight decay fix.\n Params:\n lr: learning rate\n warmup: portion of t_total for the warmup, -1 means no warmup. Default: -1\n t_total: total number of training steps for the learning\n rate schedule, -1... |
class Lamb(Optimizer):
"Implements Lamb algorithm.\n It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): ... |
def main():
if (not os.path.isdir(KALDI_ROOT)):
print('CHANGE THIS TO YOUR OWN KALDI ROOT: ', KALDI_ROOT)
exit()
if (not os.path.isdir(LIBRI_PATH)):
print('Invalid path for the kaldi librispeech dataset: ', LIBRI_PATH)
print('Please run the kaldi scripts first! More information... |
def main():
if (not os.path.isdir(KALDI_ROOT)):
print('CHANGE THIS TO YOUR OWN KALDI ROOT: ', KALDI_ROOT)
exit()
if (not os.path.isdir(TIMIT_PATH)):
print('Invalid path for the kaldi TIMIT dataset: ', TIMIT_PATH)
print('Please run the kaldi scripts first! More information are d... |
def main():
if (not os.path.isdir(KALDI_PATH)):
print('CHANGE THIS TO YOUR OWN KALDI PATH: ', KALDI_PATH)
print('Please run the kaldi scripts first to generate kaldi data directory.')
exit()
if (not os.path.isdir(OUTPUT_DIR)):
os.mkdir(OUTPUT_DIR)
for s in SETS:
pri... |
def get_preprocess_args():
parser = argparse.ArgumentParser(description='preprocess arguments for any dataset.')
parser.add_argument('-i', '--input_data', default='../LibriSpeech/', type=str, help='Path to your LibriSpeech directory', required=False)
parser.add_argument('-o', '--output_path', default='./d... |
def extract_length(input_file):
torchaudio.set_audio_backend('sox_io')
return torchaudio.info(input_file).num_frames
|
def generate_length(args, tr_set, audio_extension):
for (i, s) in enumerate(tr_set):
if os.path.isdir(os.path.join(args.input_data, s.lower())):
s = s.lower()
elif os.path.isdir(os.path.join(args.input_data, s.upper())):
s = s.upper()
else:
assert NotImp... |
def main():
args = get_preprocess_args()
if ('librilight' in args.input_data.lower()):
SETS = (['small', 'medium', 'large'] + ['small-splitted', 'medium-splitted', 'large-splitted'])
elif ('librispeech' in args.input_data.lower()):
SETS = ['train-clean-100', 'train-clean-360', 'train-other... |
def locate_txt(flac):
filename = os.path.basename(flac)
tags = filename.split('.')[0].split('-')
txt_path = os.path.join(os.path.dirname(flac), f'{tags[0]}-{tags[1]}.trans.txt')
return txt_path
|
def get_preprocess_args():
parser = argparse.ArgumentParser(description='preprocess arguments for LibriSpeech dataset.')
parser.add_argument('--data_path', default='./data/libri_alignment', type=str, help='Path to raw LibriSpeech alignment')
parser.add_argument('--output_path', default='./data/libri_phone... |
def phone_preprocess(data_path, output_path, sets, unaligned):
print('Data sets :')
for (idx, s) in enumerate(sets):
print('\t', idx, ':', s)
todo_sets = input('Please enter the index for preprocessing sets (seperate w/ space): ')
sets = [sets[int(s)] for s in todo_sets.split(' ')]
idx = 0... |
def time_to_frame(start_time, end_time, phone):
phones = []
start_time = int((start_time * sample_rate))
end_time = int((end_time * sample_rate))
(_, hop_length, win_length) = _stft_parameters(sample_rate=sample_rate)
h_window = (win_length * 0.5)
start_time = ((start_time - h_window) if (star... |
def main():
args = get_preprocess_args()
if (not os.path.exists(args.output_path)):
os.makedirs(args.output_path)
try:
file = open(os.path.join(args.data_path, 'train-clean-360/unaligned.txt')).readlines()
unaligned = [str(line).split('\t')[0].split(' ')[0] for line in file]
... |
def boolean_string(s):
if (s not in ['False', 'True']):
raise ValueError('Not a valid boolean string')
return (s == 'True')
|
def get_preprocess_args():
parser = argparse.ArgumentParser(description='preprocess arguments for any dataset.')
parser.add_argument('--output_path', default='./data/', type=str, help='Path to store output', required=False)
parser.add_argument('--audio_extention', default='.flac', type=str, help='audio fi... |
def acoustic_preprocess(args, tr_set, dim, audio_extention):
for (i, s) in enumerate(tr_set):
print('')
print('Preprocessing data in: ', s, end='')
todo = list(Path(os.path.join(args.data_root, s)).rglob(('*' + audio_extention)))
print(len(todo), 'audio files found.')
if (a... |
def main():
args = get_preprocess_args()
mel_dim = (num_mels * ((1 + int(args.delta)) + int(args.delta_delta)))
mfcc_dim = (num_mfcc * ((1 + int(args.delta)) + int(args.delta_delta)))
dim = (num_freq if (args.feature_type == 'linear') else (mfcc_dim if (args.feature_type == 'mfcc') else mel_dim))
... |
def boolean_string(s):
if (s not in ['False', 'True']):
raise ValueError('Not a valid boolean string')
return (s == 'True')
|
def get_preprocess_args():
parser = argparse.ArgumentParser(description='preprocess arguments for LibriSpeech dataset.')
parser.add_argument('--data_path', default='./data/LibriSpeech', type=str, help='Path to raw LibriSpeech dataset')
parser.add_argument('--output_path', default='./data/', type=str, help... |
def acoustic_preprocess(args, tr_set, dim):
for s in tr_set:
print('')
print('Preprocessing', s, 'data...', end='')
todo = list(Path(os.path.join(args.data_path, s)).rglob('*.flac'))
print(len(todo), 'audio files found in', s)
if (args.name == 'None'):
output_di... |
def main():
args = get_preprocess_args()
mel_dim = (num_mels * ((1 + int(args.delta)) + int(args.delta_delta)))
mfcc_dim = (num_mfcc * ((1 + int(args.delta)) + int(args.delta_delta)))
dim = (num_freq if (args.feature_type == 'linear') else (mfcc_dim if (args.feature_type == 'mfcc') else mel_dim))
... |
def boolean_string(s):
if (s not in ['False', 'True']):
raise ValueError('Not a valid boolean string')
return (s == 'True')
|
def bracket_underscore(string):
split = string.split('[')
utterance_name = split[0]
number = int(split[1].split(']')[0])
string = ((utterance_name + '_') + str((number + 1)))
return string
|
def underscore_bracket(string):
split = string.split('_')
number = int(split[(- 1)][:(- 4)])
utterance_name = '_'.join(split[:(- 1)])
string = (((utterance_name + '[') + str((number - 1))) + ']')
return string
|
def get_preprocess_args():
parser = argparse.ArgumentParser()
parser.add_argument('--flac_path', default='../../data/mosei/flac', type=str, help='Path to MOSEI segmented FLAC files')
parser.add_argument('--output_path', default='../../data/mosei', type=str, help='Path to store segmented npys', required=Fa... |
def extract_mosei(args, dim):
assert os.path.exists(args.flac_path), f'{args.flac_path} not exists'
todo = list(Path(args.flac_path).glob('*.flac'))
print(len(todo), 'audio files found in MOSEI')
assert (args.feature_type in ['mel', 'linear', 'fbank']), 'Feature type unsupported'
if (not os.path.e... |
def main():
args = get_preprocess_args()
dim = (num_freq if (args.feature_type == 'linear') else mel_dim)
extract_mosei(args, dim)
|
def get_preprocess_args():
parser = argparse.ArgumentParser()
parser.add_argument('--npy_path', default='../../data/mosei/mel160', type=str, help='Path to MOSEI segmented NPY files')
parser.add_argument('--csv_path', default='../../data/mosei/mosei_no_semi.csv', type=str, help='Path to mosei_no_semi.csv',... |
def add_length(args):
csv = pd.read_csv(args.csv_path)
lengths = []
for (index, row) in csv.iterrows():
npy = np.load(os.path.join(args.npy_path, (row.key + '.npy')))
lengths.append(npy.shape[0])
csv['length'] = lengths
csv.to_csv(args.csv_path, index=False)
|
def main():
args = get_preprocess_args()
add_length(args)
|
def bracket_underscore(string):
split = string.split('[')
utterance_name = split[0]
number = int(split[1].split(']')[0])
string = ((utterance_name + '_') + str((number + 1)))
return string
|
def underscore_bracket(string):
split = string.split('_')
number = int(split[(- 1)][:(- 4)])
utterance_name = '_'.join(split[:(- 1)])
string = (((utterance_name + '[') + str((number - 1))) + ']')
return string
|
def get_preprocess_args():
parser = argparse.ArgumentParser(description='preprocess arguments for LibriSpeech dataset.')
parser.add_argument('--data_path', default='/home/leo/d/datasets/MOSEI/Raw/Audio/Full/WAV_16000', type=str, help='Path to MOSEI non-segmented WAV files')
parser.add_argument('--output_p... |
def segment_mosei(args):
output_dir = args.output_path
mosei_summary = os.path.join(output_dir, 'mosei_no_semi.csv')
flac_dir = os.path.join(output_dir, 'flac')
assert os.path.exists(mosei_summary), 'Output path should already be created with a mosei_no_semi.csv inside it'
for target_dir in [flac_... |
def main():
args = get_preprocess_args()
segment_mosei(args)
|
def boolean_string(s):
if (s not in ['False', 'True']):
raise ValueError('Not a valid boolean string')
return (s == 'True')
|
def sdk2npy(string):
split = string.split('[')
utterance_name = split[0]
number = int(split[1].split(']')[0])
string = (((utterance_name + '_') + str((number + 1))) + '.npy')
return string
|
def npy2sdk(string):
split = string.split('_')
number = int(split[(- 1)][:(- 4)])
utterance_name = '_'.join(split[:(- 1)])
string = (((utterance_name + '[') + str((number - 1))) + ']')
return string
|
def get_preprocess_args():
parser = argparse.ArgumentParser(description='preprocess arguments for LibriSpeech dataset.')
parser.add_argument('--data_path', default='/home/leo/d/datasets/MOSI/Raw/Audio/WAV_16000/Segmented', type=str, help='Path to raw MOSI segmented audio dataset')
parser.add_argument('--o... |
def acoustic_preprocess(args, dim):
todo = list(Path(args.data_path).glob('*.wav'))
print(len(todo), 'audio files found in MOSI')
assert (args.feature_type in ['mel', 'linear', 'fbank']), 'Feature type unsupported'
output_dir = os.path.join(args.output_path, '_'.join(['mosi', (str(args.feature_type) +... |
def main():
args = get_preprocess_args()
dim = (num_freq if (args.feature_type == 'linear') else mel_dim)
acoustic_preprocess(args, dim)
|
def boolean_string(s):
if (s not in ['False', 'True']):
raise ValueError('Not a valid boolean string')
return (s == 'True')
|
def get_preprocess_args():
parser = argparse.ArgumentParser(description='preprocess arguments for LibriSpeech dataset.')
parser.add_argument('--data_path', default='./data/timit', type=str, help='Path to raw TIMIT dataset')
parser.add_argument('--output_path', default='./data/', type=str, help='Path to st... |
def preprocess(args, dim):
for s in ('train', 'dev', 'test'):
print('')
print(f'Preprocessing {s} data...', end='')
todo = list(Path(os.path.join(args.data_path, s.upper())).rglob('*.[wW][aA][vV]'))
if (len(todo) == 0):
todo = list(Path(os.path.join(args.data_path, s)).... |
def main():
args = get_preprocess_args()
mel_dim = (num_mels * ((1 + int(args.delta)) + int(args.delta_delta)))
mfcc_dim = (num_mfcc * ((1 + int(args.delta)) + int(args.delta_delta)))
dim = (num_freq if (args.feature_type == 'linear') else (mfcc_dim if (args.feature_type == 'mfcc') else mel_dim))
... |
def word_normalise(words):
ret = []
for word in words:
if (word.lower() in months):
word = months[word.lower()]
if (word.lower() in replace_words):
word = replace_words[word.lower()]
for regex in replace_vocab:
word = re.sub(regex, '', word)
... |
def sent_normalise(text, slots_split=None):
(norm_slots, norm_texts) = ([], [])
text_split = text.split(' ')
if (slots_split is None):
slots_split = (['O'] * len(text_split))
for idx in range(len(text_split)):
if (text_split[idx] in '.,!?;/]'):
continue
if (text_spl... |
def process_raw_snips_file(file, out_f):
with open(file) as f:
content = f.readlines()
content = [x.strip() for x in content]
with open(out_f, 'w') as f:
for (cnt, line) in enumerate(content):
text = line.split(' <=> ')[0]
intent = line.split(' <=> ')[1]
... |
def remove_IBO_from_snipt_vocab_slot(in_f, out_f):
with open(in_f) as f:
content = f.readlines()
content = [x.strip() for x in content]
for (idx, line) in enumerate(content):
if (line != 'O'):
content[idx] = line[len('B-'):]
content = set(content)
with open(out_f, 'w') ... |
def process_daniel_snips_file(content):
content = [x.strip() for x in content]
utt_ids = [x.split('\t', 1)[0] for x in content]
valid_uttids = [x for x in utt_ids if (x.split('-')[1] == 'valid')]
test_uttids = [x for x in utt_ids if (x.split('-')[1] == 'test')]
train_uttids = [x for x in utt_ids i... |
def map_and_link_snips_audio(snips_audio_dir, link_dir):
result = [y for x in os.walk(snips_audio_dir) for y in glob(os.path.join(x[0], '*.mp3'))]
for path in result:
person = path.split('/')[8].split('_')[1]
filename = path.split('/')[(- 1)]
if (filename[:5] != 'snips'):
c... |
def create_multispk_for_snips(output_dir):
speakers = 'Aditi Amy Brian Emma Geraint Ivy Joanna Joey Justin Kendra Kimberly Matthew Nicole Raveena Russell Salli'.split(' ')
dataset_info = [{'split': 'test', 'num_utts': 700}, {'split': 'valid', 'num_utts': 700}, {'split': 'train', 'num_utts': 13084}]
test_o... |
def apply_text_norm_and_modify_slots(all_tsv, output_dir):
(train_dirs, valid_dirs, test_dirs) = process_daniel_snips_file(all_tsv)
test_file = open(os.path.join(output_dir, 'single-matched-snips.test.w-intent'), 'w')
vocab_slot = {}
for uttid in tqdm.tqdm(test_dirs[0].keys(), desc='Text Normalising o... |
def sox_func(inputs):
(files, root, out_root, speaker) = inputs
for name in tqdm.tqdm(files, desc=('Process for speaker: ' + speaker)):
if name.endswith('.mp3'):
split = name.split('-')[1]
out_dir = os.path.join(out_root, split)
os.makedirs(out_dir, exist_ok=True)
... |
def sox_mp3_to_wav(in_root, out_root):
os.makedirs(out_root, exist_ok=True)
pool = Pool(16)
inputs = []
for (root, dirs, files) in os.walk(in_root):
print(('[Processing] enter directory %s' % root))
if (not len(files)):
continue
speaker = root.split('/')[(- 2)].spli... |
def get_preprocess_args():
parser = argparse.ArgumentParser(description='preprocess arguments for any dataset.')
parser.add_argument('-i', '--input_path', default='/livingrooms/public/LibriLight/', type=str, help='Path to your LibriSpeech directory', required=False)
parser.add_argument('-o', '--output_pat... |
def split_and_save(input_file, current_split, args):
(wav, sr) = torchaudio.load(input_file)
chunk_size = (args.split_size * sr)
(quotient, remainder) = divmod(wav.size(1), chunk_size)
sections = [chunk_size for _ in range(quotient)]
sections.append(remainder)
splitted_wav = torch.split(wav, s... |
def generate_splits(args, tr_set, audio_extension):
for (i, s) in enumerate(tr_set):
if os.path.isdir(os.path.join(args.input_path, s.lower())):
s = s.lower()
elif os.path.isdir(os.path.join(args.input_path, s.upper())):
s = s.upper()
else:
assert NotImp... |
def main():
args = get_preprocess_args()
if ('librilight' in args.input_path.lower()):
SETS = ['small', 'medium', 'large']
elif ('librispeech' in args.input_path.lower()):
SETS = ['train-clean-100', 'train-clean-360', 'train-other-500', 'dev-clean', 'dev-other', 'test-clean', 'test-other']... |
def main():
if (not os.path.isdir(KALDI_ROOT)):
print('CHANGE THIS TO YOUR OWN KALDI ROOT: ', KALDI_ROOT)
exit()
if (not os.path.isdir(INPUT_PATH)):
print('Invalid path for the preprocessed timit dataset: ', INPUT_PATH)
print("Please run 'preprocess_timit.py' first!")
e... |
class ApcAudioDataset(FeatDataset):
def __init__(self, extracter, task_config, bucket_size, file_path, sets, max_timestep=0, libri_root=None, **kwargs):
super(ApcAudioDataset, self).__init__(extracter, task_config, bucket_size, file_path, sets, max_timestep, libri_root, **kwargs)
def _load_feat(self... |
class FeatDataset(Dataset):
'Base On-the-fly feature dataset by Andy T. Liu'
def __init__(self, extracter, task_config, bucket_size, file_path, sets, max_timestep=0, libri_root=None, **kwargs):
super(FeatDataset, self).__init__()
self.extracter = extracter
self.task_config = task_conf... |
class WaveDataset(Dataset):
'Base waveform dataset for Disiller by Heng-Jui Chang'
def __init__(self, task_config, bucket_size, file_path, sets, max_timestep=0, libri_root=None, **kwargs):
super().__init__()
self.task_config = task_config
self.libri_root = libri_root
self.samp... |
def freeze_model(model):
'Freeze all parameters in a model.'
for param in model.parameters():
param.requires_grad = False
|
class UpstreamPretrainExpert(nn.Module):
'\n The Distiller pretrain expert\n '
def __init__(self, datarc, upstream_config, device='cuda', multi_gpu=False, **kwargs):
super().__init__()
self.datarc = datarc
self.device = device
self.multi_gpu = multi_gpu
if (type(... |
class DistillerForPretrain(nn.Module):
'\n Distiller for pretraining\n '
def __init__(self, config: DistillerConfig, teacher_config: edict):
super().__init__()
self.config = config
self.distiller = DistillerModel(config)
self.teacher_config = teacher_config
teach... |
class KaldiAcousticDataset(FeatDataset):
def __init__(self, extracter, task_config, bucket_size, file_path, sets, max_timestep=0, libri_root=None, **kwargs):
super(KaldiAcousticDataset, self).__init__(extracter, task_config, bucket_size, file_path, sets, max_timestep, libri_root, **kwargs)
def _load... |
class OnlineAcousticDataset(FeatDataset):
def __init__(self, extracter, task_config, bucket_size, file_path, sets, max_timestep=0, libri_root=None, target_level=(- 25), **kwargs):
max_timestep *= 160
super(OnlineAcousticDataset, self).__init__(extracter, task_config, bucket_size, file_path, sets,... |
class UpstreamPretrainExpert(nn.Module):
'\n The Mockingjay pretrain expert\n '
def __init__(self, datarc, upstream_config, device='cuda', multi_gpu=False, **kwargs):
super(UpstreamPretrainExpert, self).__init__()
self.datarc = datarc
self.device = device
self.multi_gpu ... |
class TransformerForMaskedAcousticModel(TransformerInitModel):
"\n Transformer model with the masked acoustic modeling head.\n This module comprises the Transformer model followed by the masked acoustic modeling head.\n\n Params:\n `config`: a TransformerConfig class instance with the conf... |
class ApcAudioDataset(FeatDataset):
def __init__(self, extracter, task_config, bucket_size, file_path, sets, max_timestep=0, libri_root=None, **kwargs):
super(ApcAudioDataset, self).__init__(extracter, task_config, bucket_size, file_path, sets, max_timestep, libri_root, **kwargs)
def _load_feat(self... |
class Runner():
'\n Used to handle high-level concepts of a ML experiment\n eg. training loop, evaluation loop, upstream propagation, optimization, tensorboard logging, checkpoint saving\n '
def __init__(self, args, config):
self.args = args
self.config = config
self.logger =... |
class KaldiAcousticDataset(_KaldiAcousticDataset):
def __init__(self, extracter, task_config, bucket_size, file_path, sets, max_timestep=0, libri_root=None, **kwargs):
super(KaldiAcousticDataset, self).__init__(extracter, task_config, bucket_size, file_path, sets, max_timestep, libri_root, **kwargs)
... |
class OnlineAcousticDataset(_OnlineAcousticDataset):
def __init__(self, extracter, task_config, bucket_size, file_path, sets, max_timestep=0, libri_root=None, target_level=(- 25), **kwargs):
super(OnlineAcousticDataset, self).__init__(extracter, task_config, bucket_size, file_path, sets, max_timestep, li... |
class UpstreamPretrainExpert(MockingjayPretrainExpert):
'\n The spec augment transformer pretrain expert\n '
def __init__(self, datarc, upstream_config, device='cuda', multi_gpu=False, **kwargs):
super(UpstreamPretrainExpert, self).__init__(datarc, upstream_config, device, multi_gpu, **kwargs)
... |
class ASR(Problem):
def run(self, target_dir: str, cache_dir: str, remove_all_cache: bool=False, start: int=0, stop: int=None, num_workers: int=6, eval_batch: int=(- 1), device: str='cuda', world_size: int=1, rank: int=0, test_ckpt_dir: str=None, prepare_data: dict=None, prepare_tokenizer_data: dict=None, build_... |
def prepare_librispeech(target_dir, cache_dir, dataset_root, train_sets: List[str], valid_sets: List[str], test_sets: List[str], n_jobs: int=6, get_path_only: bool=False):
'\n Prepare LibriSpeech for ASR following :obj:`SuperbASR.prepare_data` format.\n See :obj:`LibriSpeech` for the arguments usage\n '
... |
def prepare_common_tokenizer(target_dir, cache_dir, tokenizer_data_path, get_path_only=False, tokenizer_name: str=None, vocab_file: str=None, vocab_type: str='character', vocab_args: dict=None, slots_file: str=None):
'\n Build the tokenizer following :obj:`SuperbASR.build_tokenizer` format\n\n Args:\n ... |
class SuperbASR(ASR):
def default_config(self) -> dict:
return dict(start=0, stop=None, target_dir=MISSING, cache_dir=None, remove_all_cache=False, prepare_data=dict(dataset_root=MISSING, train_sets=['train-clean-100'], valid_sets=['dev-clean'], test_sets=['test-clean']), prepare_tokenizer_data=dict(), b... |
class SuperbPR(SuperbASR):
def default_config(self) -> dict:
return dict(start=0, stop=None, target_dir=MISSING, cache_dir=None, remove_all_cache=False, prepare_data=dict(dataset_root=MISSING, train_sets=['train-clean-100'], valid_sets=['dev-clean'], test_sets=['test-clean']), prepare_tokenizer_data=dict... |
def audio_snips_for_slot_filling(target_dir: str, cache_dir: str, dataset_root: str, train_speakers: List[str], valid_speakers: List[str], test_speakers: List[str], get_path_only: bool=False):
target_dir = Path(target_dir)
train_path = (target_dir / f'train.csv')
valid_path = (target_dir / f'valid.csv')
... |
class SuperbSF(SuperbASR):
def default_config(self) -> dict:
return dict(start=0, stop=None, target_dir=MISSING, cache_dir=None, remove_all_cache=False, prepare_data=dict(dataset_root=MISSING, train_speakers=['Ivy', 'Joanna', 'Joey', 'Justin', 'Kendra', 'Kimberly', 'Matthew', 'Salli'], valid_speakers=['A... |
class ASV(Problem):
def run(self, target_dir: str, cache_dir: str, remove_all_cache: bool=False, start: int=0, stop: int=None, num_workers: int=6, eval_batch: int=(- 1), device: str='cuda', world_size: int=1, rank: int=0, test_ckpt_dir: str=None, test_ckpt_steps: List[int]=None, prepare_data: dict=None, build_en... |
def prepare_voxceleb1_for_sv(target_dir: str, cache_dir: str, get_path_only: str, dataset_root: str, force_download: bool=False):
'\n Prepare VoxCeleb1 for speaker verification\n following :obj:`SuperbASV.prepare_data` format.\n\n Args:\n dataset_root (str): The root path of Fluent Speech Command\... |
class SuperbASV(ASV):
def default_config(self):
return dict(target_dir=MISSING, cache_dir=None, test_ckpt_steps=None, prepare_data=dict(dataset_root=MISSING), build_dataset=dict(train=dict(min_secs=2.0, max_secs=8.0)), build_batch_sampler=dict(train=dict(batch_size=10, shuffle=True), test=dict(batch_size... |
class _DistributedDataParallel(torch.nn.parallel.DistributedDataParallel):
def __getattr__(self, name):
try:
return super().__getattr__(name)
except AttributeError:
return getattr(self.module, name)
|
def _force_cacheable(data: dict):
output = dict()
for (key, value) in data.items():
if isinstance(value, torch.Tensor):
value = value.detach().cpu()
output[key] = value
return output
|
def _to_device(data, device: str):
output = dict()
for (key, value) in data.items():
if isinstance(value, torch.Tensor):
value = value.to(device)
output[key] = value
return output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.