code
stringlengths
17
6.64M
def _doc_default_config(cls: Problem): "\n This is used to layout the :code:`default_config` dictionary into yaml format\n for :code:`default_config`'s docstring.\n " def _append_prefix_spaces(docstring: str): return '\n'.join([f' {line}' for line in docstring.split('\n')]) obj = cls() ...
class Problem(): _store: Dict[(str, Problem)] = dict() def __init_subclass__(cls) -> None: super().__init_subclass__() cls._store[cls.__name__] = cls _doc_default_config(cls) @classmethod def get_class_from_name(cls, name: str): '\n Args:\n name (str...
def resample_hear_corpus(task_dir: str, target_sr: int=16000, num_workers: int=6): '\n Resample audio files in\n\n ${task_dir}/48000/\n\n to\n\n ${task_dir}/${target_sr}/\n ' task_dir: Path = Path(task_dir) target_audio_dir: Path = (task_dir / f'{target_sr}') if target_audio_dir.is_dir(...
class CommonExample(SuperbSID): def default_config(self) -> dict: config = super().default_config() config['prepare_data'] = {} config['train'] = dict(total_steps=10, log_step=1, eval_step=5, save_step=5, gradient_clipping=1.0, gradient_accumulate=1, valid_metric='accuracy', valid_higher_...
class HearBeijingOpera(HearESC50): 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, test_fold=MISSING, num_folds=BEIJING_OPERA_NUM_FOLDS), build_batch_sampler=dict(train=dict(batch_size=32...
class HearCremaD(HearESC50): 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, test_fold=MISSING, num_folds=CREMAD_NUM_FOLDS), build_batch_sampler=dict(train=dict(batch_size=32, shuffle=Tru...
def dcase_2016_task2(target_dir: str, cache_dir: str, dataset_root: str, get_path_only: bool=False): target_dir: Path = Path(target_dir) train_csv = (target_dir / 'train.csv') valid_csv = (target_dir / 'valid.csv') test_csv = (target_dir / 'test.csv') if get_path_only: return (train_csv, v...
class HearDcase2016Task2(HearFSD): 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), build_dataset=dict(train=dict(chunk_secs=4.0, step_secs=4.0), valid=dict(chunk_secs=4.0, step_secs=4.0)...
def hear_scene_kfolds(target_dir: str, cache_dir: str, dataset_root: str, test_fold: int, num_folds: int, get_path_only: bool=False): assert (test_fold < num_folds), f'test_fold id must be smaller than num_folds. get test_fold={test_fold} and num_folds={num_folds}' target_dir = Path(target_dir) train_csv ...
class HearESC50(HearFSD): 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, test_fold=MISSING, num_folds=ESC50_NUM_FOLDS), build_batch_sampler=dict(train=dict(batch_size=32, shuffle=True), ...
def hear_scene_trainvaltest(target_dir: str, cache_dir: str, dataset_root: str, get_path_only: bool=False): target_dir = Path(target_dir) resample_hear_corpus(dataset_root, target_sr=16000) dataset_root = Path(dataset_root) wav_root: Path = (dataset_root / '16000') train_csv = (target_dir / 'train...
class HearFSD(SuperbSID): 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), build_batch_sampler=dict(train=dict(batch_size=10, shuffle=True), valid=dict(batch_size=1), test=dict(batch_size...
class HearGSC5hr(HearFSD): 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), build_batch_sampler=dict(train=dict(batch_size=32, shuffle=True), valid=dict(batch_size=1), test=dict(batch_siz...
class HearGtzan(HearESC50): 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, test_fold=MISSING, num_folds=GTZAN_NUM_FOLDS), build_batch_sampler=dict(train=dict(batch_size=32, shuffle=True)...
class HearGtzanMusicSpeech(HearESC50): 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, test_fold=MISSING, num_folds=GTZAN_MUSIC_SPEECH_NUM_FOLDS), build_batch_sampler=dict(train=dict(batc...
class HearGunshot(HearESC50): 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, test_fold=MISSING, num_folds=GUNSHOT_NUM_FOLDS), build_batch_sampler=dict(train=dict(batch_size=32, shuffle=T...
class HearLibriCount(HearESC50): 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, test_fold=MISSING, num_folds=LIBRICOUNT_NUM_FOLDS), build_batch_sampler=dict(train=dict(batch_size=32, shu...
def prepare_maestro(target_dir: str, cache_dir: str, dataset_root: str, test_fold: int=0, get_path_only: bool=False): target_dir: Path = Path(target_dir) train_csv = (target_dir / 'train.csv') valid_csv = (target_dir / 'valid.csv') test_csv = (target_dir / 'test.csv') if get_path_only: ret...
class HearMaestro(HearDcase2016Task2): 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, test_fold=MISSING), build_batch_sampler=dict(train=dict(batch_size=5, shuffle=True), valid=dict(item...
class HearNsynth5hr(HearFSD): 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), build_batch_sampler=dict(train=dict(batch_size=32, shuffle=True), valid=dict(batch_size=1), test=dict(batch_...
class HearStroke(HearESC50): 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, test_fold=MISSING, num_folds=STROKE_NUM_FOLDS), build_batch_sampler=dict(train=dict(batch_size=32, shuffle=Tru...
class HearTonic(HearESC50): 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, test_fold=MISSING, num_folds=TONIC_NUM_FOLDS), build_batch_sampler=dict(train=dict(batch_size=32, shuffle=True)...
class HearVocal(HearESC50): 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, test_fold=MISSING, num_folds=VOCAL_NUM_FOLDS), build_batch_sampler=dict(train=dict(batch_size=32, shuffle=True)...
class HearVoxLingual(HearESC50): 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, test_fold=MISSING, num_folds=VOX_LINQUAL_NUM_FOLDS), build_batch_sampler=dict(train=dict(batch_size=32, sh...
class Common(Problem): def run(self, target_dir: str, cache_dir: str=None, 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, build_encoder: dict=None, build_d...
def iemocap_for_superb(target_dir: str, cache_dir: str, iemocap: str, test_fold: int, valid_ratio: float=0.2, get_path_only: bool=False): '\n Prepare IEMOCAP for emotion classfication with SUPERB protocol,\n following :obj:`SuperbER.prepare_data` format.\n\n .. note::\n\n In SUPERB protocol, you n...
class SuperbER(SuperbSID): def default_config(self) -> dict: return dict(start=0, stop=None, target_dir=MISSING, cache_dir=None, remove_all_cache=False, prepare_data=dict(iemocap=MISSING, test_fold=MISSING), build_encoder=dict(), build_dataset=dict(), build_batch_sampler=dict(train=dict(batch_size=4, shu...
def fsc_for_multi_classification(target_dir: str, cache_dir: str, dataset_root: str, n_jobs: int=6, get_path_only: bool=False): '\n Prepare Fluent Speech Command for multi-class classfication\n following :obj:`SuperbIC.prepare_data` format. The standard usage\n is to use three labels jointly: action, obj...
class SuperbIC(Common): 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), build_encoder=dict(), build_dataset=dict(), build_batch_sampler=dict(train=dict(batch_size=32, shuffle=True), vali...
def gsc1_for_classification(target_dir: str, cache_dir: str, gsc1: str, gsc1_test: str, get_path_only: bool=False): '\n Prepare Google Speech Command for classfication task\n following :obj:`SuperbKS.prepare_data` format.\n\n Args:\n gsc1 (str): The root path of the Google Speech Command V1 traini...
class SuperbKS(SuperbSID): def default_config(self) -> dict: return dict(start=0, stop=None, target_dir=MISSING, cache_dir=None, remove_all_cache=False, prepare_data=dict(gsc1=MISSING, gsc1_test=MISSING), build_encoder=dict(), build_dataset=dict(train=dict(sox_effects=[['channels', '1'], ['rate', '16000'...
def voxceleb1_for_sid(target_dir: str, cache_dir: str, dataset_root: str, n_jobs: int=6, get_path_only: bool=False): '\n Prepare VoxCeleb1 for SID following :obj:`SuperbSID.prepare_data` format.\n\n Args:\n dataset_root (str): The root path of VoxCeleb1\n n_jobs (int): to speed up the corpus p...
class SuperbSID(Common): '\n The standard SUPERB SID task\n ' 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), build_encoder=dict(), build_dataset=dict(train=dict(max_secs=8.0))...
class Diarization(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, num_speaker: int=2, prepare_data: dict=None, build_dataset...
class SuperbSD(Diarization): def default_config(self): return dict(start=0, stop=None, target_dir=MISSING, cache_dir=None, remove_all_cache=False, prepare_data=dict(data_dir=MISSING), build_dataset=dict(chunk_size=2000, subsampling=1, rate=16000, use_last_samples=True, label_delay=0), build_batch_sampler...
def kaldi_dir_to_rttm(data_dir: str, rttm_path: str): data_dir: Path = Path(data_dir) segments_file = (data_dir / 'segments') utt2spk_file = (data_dir / 'utt2spk') assert segments_file.is_file() assert utt2spk_file.is_file() utt2spk = {} with utt2spk_file.open() as f: for utt2spk_l...
def make_rttm_and_score(prediction_dir: str, score_dir: str, gt_rttm: str, frame_shift: int, thresholds: List[int], medians: List[int], subsampling: int=1, sampling_rate: int=16000): Path(score_dir).mkdir(exist_ok=True, parents=True) dscore_dir = (Path(score_dir) / 'dscore') rttm_dir = (Path(score_dir) / ...
def make_rttm(prediction_dir: str, out_rttm_path: str, threshold: int, median: int, frame_shift: int, subsampling: int, sampling_rate: int): names = sorted([name for name in os.listdir(prediction_dir)]) filepaths = [(Path(prediction_dir) / name) for name in names] Path(out_rttm_path).parent.mkdir(exist_ok...
def score_with_dscore(dscore_dir: str, hyp_rttm: str, gt_rttm: str, score_result: str) -> float: "\n This function returns the overall DER score, and will also write the detailed scoring results\n to 'score_result'\n " dscore_dir: Path = Path(dscore_dir) Path(score_result).parent.mkdir(exist_ok=T...
def get_overall_der_from_dscore_file(score_result: str): with open(score_result) as file: lines = file.readlines() overall_lines = [line for line in lines if ('OVERALL' in line)] assert (len(overall_lines) == 1) overall_line = overall_lines[0] overall_line = re.sub('\t+', '...
def csv_to_kaldi_dir(csv: str, data_dir: str): logger.info(f'Convert csv {csv} into kaldi data directory {data_dir}') data_dir: Path = Path(data_dir) data_dir.mkdir(exist_ok=True, parents=True) df = pd.read_csv(csv) required = ['record_id', 'wav_path', 'utt_id', 'speaker', 'start_sec', 'end_sec'] ...
def kaldi_dir_to_csv(data_dir: str, csv: str): logger.info(f'Convert kaldi data directory {data_dir} into csv {csv}') data_dir: Path = Path(data_dir) assert (data_dir / 'wav.scp').is_file() assert (data_dir / 'segments').is_file() assert (data_dir / 'utt2spk').is_file() assert (data_dir / 'rec...
class BeijingOpera(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold=field('???', 'The testing fold id. Options:...
class CremaD(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold='???', num_folds=NUM_FOLDS), train_sampler=dict(b...
class Dcase2016Task2(HearTimestamp): @default_cfg(**HearTimestamp.setup.default_except(corpus=dict(CLS=field(dcase_2016_task2, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str)), downstream=dict(CLS=field(HearFullyConnecte...
class ESC50(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold=field('???', 'The testing fold id. Options: [0, 1,...
class FSD50k(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_trainvaltest, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str)), train_sampler=newdict(CLS=FixedBatchSizeBatchSampler...
class GSC5hr(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_trainvaltest, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str)), train_sampler=dict(batch_size=32), task=dict(predict...
class Gtzan(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold='???', num_folds=NUM_FOLDS), train_sampler=dict(ba...
class GtzanMusicSpeech(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold='???', num_folds=NUM_FOLDS), train_samp...
class Gunshot(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold=field('???', 'The testing fold id. Options: [0, ...
class LibriCount(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold=field('???', 'The testing fold id. Options: [...
class Maestro(HearTimestamp): @default_cfg(**HearTimestamp.setup.default_except(corpus=dict(CLS=field(maestro, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold=field('???', 'The testing fold id. Options: [0, 1,...
class Nsynth5hr(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_trainvaltest, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str)), train_sampler=dict(batch_size=32), task=dict(pred...
class HearScene(Problem, Trainer): @default_cfg(workspace=field('???', "\nWill put the following keys into this workspace:\n 'train_dataset', 'train_sampler', 'valid_dataset', 'valid_sampler', and 'task'", 'str or Path or Workspace'), corpus=dict(CLS=field('???', '\nThe corpus class. You can add the **kwargs ri...
class Stroke(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold=field('???', 'The testing fold id. Options: [0, 1...
class HearTimestamp(Problem, Trainer): @default_cfg(workspace=field('???', "\nWill put the following keys into this workspace:\n 'train_dataset', 'train_sampler', 'valid_dataset', 'valid_sampler', and 'task'", 'str or Path or Workspace'), corpus=dict(CLS=field('???', '\nThe corpus class. You can add the **kwarg...
class Tonic(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold=field('???', 'The testing fold id. Options: [0, 1,...
class Vocal(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold='???', num_folds=NUM_FOLDS), train_sampler=dict(ba...
class VoxLingua(HearScene): @default_cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_kfolds, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str), test_fold=field('???', 'The testing fold id. Options: [0...
class Apc(SslProblem): '\n Apc pre-train problem\n ' @override_parent_cfg(corpus=dict(_cls=librispeech_for_pretrain, dataset_root='???'), train_datapipe=_pretrain_task_pipe_config, train_sampler=dict(_cls=MaxTimestampBatchSampler, max_timestamp=(16000 * 20), shuffle=True), valid_datapipe=_pretrain_task...
class AudioAlbert(SslProblem): '\n AudioAlbert pre-train problem\n ' @override_parent_cfg(corpus=dict(_cls=librispeech_for_pretrain, dataset_root='???'), train_datapipe=_pretrain_task_pipe_config, train_sampler=dict(_cls=MaxTimestampBatchSampler, max_timestamp=(16000 * 20), shuffle=True), valid_datapip...
class SslProblem(Problem, Trainer): @default_cfg(workspace=field('???', "\nWill put the following keys into this workspace:\n 'train_dataset', 'train_sampler', 'valid_dataset', 'valid_sampler', and 'task'", 'str or Path or Workspace'), corpus=dict(_cls=field('???', '\nThe corpus class. You can add the **kwargs ...
class Mockingjay(SslProblem): '\n Mockingjay pre-train problem\n ' @override_parent_cfg(corpus=dict(_cls=librispeech_for_pretrain, dataset_root='???'), train_datapipe=pretrain_task_pipe_config, train_sampler=dict(_cls=MaxTimestampBatchSampler, max_timestamp=(16000 * 20), shuffle=True), valid_datapipe=p...
class Npc(SslProblem): '\n Npc pre-train problem\n ' @override_parent_cfg(corpus=dict(_cls=librispeech_for_pretrain, dataset_root='???'), train_datapipe=_pretrain_task_pipe_config, train_sampler=dict(_cls=MaxTimestampBatchSampler, max_timestamp=(16000 * 20), shuffle=True), valid_datapipe=_pretrain_task...
class Tera(SslProblem): '\n Tera pre-train problem\n ' @override_parent_cfg(corpus=dict(_cls=librispeech_for_pretrain, dataset_root='???'), train_datapipe=_pretrain_task_pipe_config, train_sampler=dict(_cls=MaxTimestampBatchSampler, max_timestamp=(16000 * 20), shuffle=True), valid_datapipe=_pretrain_ta...
class VqApc(SslProblem): '\n VqApc pre-train problem\n ' @override_parent_cfg(corpus=dict(_cls=librispeech_for_pretrain, dataset_root='???'), train_datapipe=_pretrain_task_pipe_config, train_sampler=dict(_cls=MaxTimestampBatchSampler, max_timestamp=(16000 * 20), shuffle=True), valid_datapipe=_pretrain_...
class SuperbASR(SuperbProblem): @default_cfg(**SuperbProblem.setup.default_except(corpus=dict(CLS=librispeech_for_speech2text, dataset_root='???'), train_datapipe=dict(CLS=Speech2TextPipe, generate_tokenizer=True), train_sampler=dict(CLS=SortedBucketingSampler, batch_size=32, max_length=2000, shuffle=True), vali...
class SuperbProblem(Problem, Trainer): @default_cfg(workspace=field('???', "\nWill put the following keys into this workspace:\n 'train_dataset', 'train_sampler', 'valid_dataset', 'valid_sampler', and 'task'", 'str or Path or Workspace'), corpus=dict(CLS=field('???', '\nThe corpus class. You can add the **kwarg...
class SuperbER(SuperbProblem): '\n Superb Emotion Classification problem\n ' @default_cfg(**SuperbProblem.setup.default_except(corpus=dict(CLS=iemocap_for_superb, dataset_root='???', test_fold=field('???', 'The session in IEMOCAP used for testing.\nThe other sessions will be used for training and valid...
class SuperbIC(SuperbProblem): '\n Superb Intent Classification problem\n ' @default_cfg(**SuperbProblem.setup.default_except(corpus=dict(CLS=fsc_for_multiple_classfication, dataset_root='???'), train_datapipe=dict(CLS=UtteranceMultipleCategoryClassificationPipe, train_category_encoder=True), train_sam...
class SuperbKS(SuperbProblem): @default_cfg(**SuperbProblem.setup.default_except(corpus=dict(CLS=gsc_v1_for_superb, dataset_root='???'), train_datapipe=dict(CLS=UtteranceClassificationPipe, train_category_encoder=True, sox_effects=EFFECTS), train_sampler=dict(CLS=BalancedWeightedSampler, batch_size=32), valid_da...
class SuperbPR(SuperbProblem): @default_cfg(**SuperbProblem.setup.default_except(corpus=dict(CLS=librispeech_for_speech2text, dataset_root='???'), train_datapipe=dict(CLS=Speech2PhonemePipe), train_sampler=dict(CLS=SortedSliceSampler, batch_size=16, max_length=300000), valid_datapipe=dict(CLS=Speech2PhonemePipe)...
class SuperbSDDatapipe(SequentialDataPipe): def __init__(self, feat_frame_shift: int, sample_rate: int=16000, **kwds): super().__init__(UnfoldChunkByFrame(min_chunk_frames=2000, max_chunk_frames=2000, step_frames=2000, feat_frame_shift=feat_frame_shift, sample_rate=sample_rate), BuildMultiClassTagging(sa...
def prediction_numpy_to_segment_secs(prediction: np.ndarray, threshold: float=0.5, median_filter: int=1, frame_shift: int=160, subsampling: int=1, sampling_rate: int=16000): '\n prediction: (timestamps, class_num), all values are in 0~1\n ' hard_pred = np.where((prediction > threshold), 1, 0) if (me...
class SuperbSD(SuperbProblem): '\n Superb Intent Classification problem\n ' @default_cfg(**SuperbProblem.setup.default_except(corpus=dict(CLS=kaldi_for_multiclass_tagging, dataset_root='???'), train_datapipe=dict(CLS=SuperbSDDatapipe, train_category_encoder=True), train_sampler=dict(CLS=FixedBatchSizeB...
class SuperbSF(SuperbProblem): @default_cfg(**SuperbProblem.setup.default_except(corpus=dict(CLS=snips_for_speech2text, dataset_root='???'), train_datapipe=dict(CLS=Speech2TextPipe, generate_tokenizer=True, vocab_type='character-slot', vocab_file=_urls_to_filepaths(VOCAB_URL), slots_file=_urls_to_filepaths(SLOTS...
class SuperbSIDTrainPipe(DataPipe): def __init__(self, train_category_encoder: bool=False, max_secs: float=None) -> None: self.pipes = SequentialDataPipe(UtteranceClassificationPipe(train_category_encoder=train_category_encoder), RandomCrop(max_secs=max_secs), SetOutputKeys(dict(x='wav_crop', x_len='wav_...
class SuperbSID(SuperbProblem): '\n Superb SID\n ' @default_cfg(**SuperbProblem.setup.default_except(corpus=dict(CLS=voxceleb1_for_utt_classification, dataset_root='???'), train_datapipe=dict(CLS=SuperbSIDTrainPipe, train_category_encoder=True, max_secs=8.0), train_sampler=dict(CLS=FixedBatchSizeBatchS...
class SuperbSV(SuperbProblem): '\n Superb Speaker Verification problem\n ' @default_cfg(**SuperbProblem.setup.default_except(corpus=dict(CLS=voxceleb1_for_sv, dataset_root='???'), train_datapipe=dict(CLS=SpeakerVerificationPipe, random_crop_secs=8.0, sox_effects=EFFECTS), train_sampler=dict(CLS=FixedBa...
def get_downstream_args(): parser = argparse.ArgumentParser() parser.add_argument('-m', '--mode', choices=['train', 'evaluate', 'inference'], required=True) parser.add_argument('-t', '--evaluate_split', default='test') parser.add_argument('-o', '--override', help='Used to override args and config, thi...
def main(): logging.basicConfig(level=logging.INFO) torch.multiprocessing.set_sharing_strategy('file_system') torchaudio.set_audio_backend('sox_io') hack_isinstance() (args, config, backup_files) = get_downstream_args() if (args.cache_dir is not None): torch.hub.set_dir(args.cache_dir)...
def get_pretrain_args(): parser = argparse.ArgumentParser() parser.add_argument('-e', '--past_exp', metavar='{CKPT_PATH,CKPT_DIR}', help='Resume training from a checkpoint') parser.add_argument('-o', '--override', help='Used to override args and config, this is at the highest priority') parser.add_arg...
def main(): (args, config) = get_pretrain_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 = Fals...
def get_scheduler(optimizer, total_steps, scheduler_config): scheduler_config = copy.deepcopy(scheduler_config) scheduler_name = scheduler_config.pop('name') scheduler = eval(f'get_{scheduler_name}')(optimizer, num_training_steps=total_steps, **scheduler_config) return scheduler
def get_cosine_with_hard_restarts_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: int=1, last_epoch: int=(- 1)): '\n Create a schedule with a learning rate that decreases following the values of the cosine function between the\n initial lr set in the op...
def get_cosine_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float=0.5, last_epoch: int=(- 1)): '\n Create a schedule with a learning rate that decreases following the values of the cosine function between the\n initial lr set in the optimizer to 0, a...
def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=(- 1)): '\n Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0,\n after a warmup period during which it increases linearly from 0 to the initial lr set in...
def get_sqrt_decay_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=(- 1)): '\n Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0,\n after a warmup period during which it increases linearly from 0 to the initial lr se...
def get_constant_decay_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=(- 1)): '\n Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0,\n after a warmup period during which it increases linearly from 0 to the initial l...
def get_noam_decay_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=(- 1)): '\n Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0,\n after a warmup period during which it increases linearly from 0 to the initial lr se...
def get_polynomial_decay_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, lr_end=1e-07, power=1.0, last_epoch=(- 1)): '\n Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the\n optimizer to end lr defined by `lr_end`, after a warmup ...
def label_vocab_as_dict(df: pd.DataFrame, key: str, value: str) -> Dict: '\n Returns a dictionary of the label vocabulary mapping the label column to\n the idx column. key sets whether the label or idx is the key in the dict. The\n other column will be the value.\n ' if (key == 'label'): d...
def label_to_binary_vector(label: List, num_labels: int) -> torch.Tensor: '\n Converts a list of labels into a binary vector\n Args:\n label: list of integer labels\n num_labels: total number of labels\n\n Returns:\n A float Tensor that is multi-hot binary vector\n ' if (len(l...
def validate_score_return_type(ret: Union[(Tuple[(Tuple[(str, float)], ...)], float)]): '\n Valid return types for the metric are\n - tuple(tuple(string: name of the subtype, float: the value)): This is the\n case with sed eval metrics. They can return (("f_measure", value),\n ("pr...
class ScoreFunction(): '\n A simple abstract base class for score functions\n ' def __init__(self, label_to_idx: Dict[(str, int)], name: Optional[str]=None, maximize: bool=True): "\n :param label_to_idx: Map from label string to integer index.\n :param name: Override the name of t...
class Top1Accuracy(ScoreFunction): name = 'top1_acc' def _compute(self, predictions: np.ndarray, targets: np.ndarray, **kwargs) -> float: assert (predictions.ndim == 2) assert (targets.ndim == 2) correct = 0 for (target, prediction) in zip(targets, predictions): as...
class ChromaAccuracy(ScoreFunction): '\n Score specifically for pitch detection -- converts all pitches to chroma first.\n This score ignores octave errors in pitch classification.\n ' name = 'chroma_acc' def _compute(self, predictions: np.ndarray, targets: np.ndarray, **kwargs) -> float: ...
class SoundEventScore(ScoreFunction): '\n Scores for sound event detection tasks using sed_eval\n ' score_class: sed_eval.sound_event.SoundEventMetrics = None def __init__(self, label_to_idx: Dict[(str, int)], scores: Tuple[str], params: Dict=None, name: Optional[str]=None, maximize: bool=True): ...
class SegmentBasedScore(SoundEventScore): '\n segment-based scores - the ground truth and system output are compared in a\n fixed time grid; sound events are marked as active or inactive in each segment;\n\n See https://tut-arg.github.io/sed_eval/sound_event.html#sed_eval.sound_event.SegmentBasedMetrics ...