code stringlengths 17 6.64M |
|---|
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 ... |
class EventBasedScore(SoundEventScore):
'\n event-based scores - the ground truth and system output are compared at\n event instance level;\n\n See https://tut-arg.github.io/sed_eval/generated/sed_eval.sound_event.EventBasedMetrics.html # noqa: E501\n for params.\n '
score_class = sed_eval.soun... |
class MeanAveragePrecision(ScoreFunction):
'\n Average Precision is calculated in macro mode which calculates\n AP at a class level followed by macro-averaging across the classes.\n '
name = 'mAP'
def _compute(self, predictions: np.ndarray, targets: np.ndarray, **kwargs) -> float:
assert... |
class DPrime(ScoreFunction):
'\n DPrime is calculated per class followed by averaging across the classes\n\n Code adapted from code provided by Eduoard Fonseca.\n '
name = 'd_prime'
def _compute(self, predictions: np.ndarray, targets: np.ndarray, **kwargs) -> float:
assert (predictions.n... |
class AUCROC(ScoreFunction):
'\n AUCROC (macro mode) is calculated per class followed by averaging across the\n classes\n '
name = 'aucroc'
def _compute(self, predictions: np.ndarray, targets: np.ndarray, **kwargs) -> float:
assert (predictions.ndim == 2)
assert (targets.ndim == ... |
class AutoregressiveReconstructionTask(Task):
'\n Attributes:\n upstream (torch.nn.Module): The upstream encoder (transformers, rnn, etc) that outputs `hidden_states`\n predictor (torch.nn.Module): The pre-training predictor that takes `hidden_states` as input and maps to the task target\n ... |
class Task(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
def get_state(self):
return {}
def set_state(self, state: dict):
pass
def parse_cached_results(self, cached_results: List[dict]):
keys = list(cached_results[0].keys())
dol = defaultd... |
class FeatReconstructionTask(Task):
'\n Attributes:\n upstream (torch.nn.Module): The upstream encoder (transformers, rnn, etc) that outputs `hidden_states`\n predictor (torch.nn.Module): The pre-training predictor that takes `hidden_states` as input and maps to the task target\n loss (tor... |
class OneHotToCrossEntropyLoss(torch.nn.Module):
def __init__(self):
super().__init__()
self.loss = torch.nn.CrossEntropyLoss()
def forward(self, y_hat: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
assert torch.all((torch.sum(y, dim=1) == y.new_ones(y.shape[0])))
y = y.arg... |
class ScenePredictionTask(Task):
def __init__(self, model: torch.nn.Module, category: CategoryEncoder, prediction_type: str, scores: List[str]):
super().__init__()
self.model = model
self.label_to_idx = {str(category.decode(idx)): idx for idx in range(len(category))}
self.idx_to_l... |
class SpeakerClassifier(torch.nn.Module):
'\n Attributes:\n input_size: int\n output_size: int\n '
def __init__(self, input_size=3, output_size=4):
super().__init__()
self._input_size = input_size
self._output_size = output_size
@property
def input_size(se... |
class SpeakerVerification(Task):
'\n model.output_size should match len(categories)\n\n Args:\n model (SpeakerClassifier):\n actual model or a callable config for the model\n categories (dict[str]):\n each key in the Dictionary is the final prediction content in str.\n ... |
class Speech2TextCTCExample(nn.Module):
'An example speech-to-text task with CTC objective\n\n Args:\n input_size (int, optional): Input size. Defaults to 3.\n output_size (int, optional): Output size. Defaults to 4.\n '
def __init__(self, input_size=3, output_size=4):
super().__i... |
class Speech2TextCTCTask(Task):
'Speech-to-text task with CTC objective\n\n Args:\n model (Speech2TextCTCExample)\n tokenizer (Tokenizer): Text tokenizer.\n decoder (Union[BeamDecoder, dict], optional):\n Beam decoder or decoder\'s config. Defaults to None.\n log_metrics ... |
class CMVN(nn.Module):
__constants__ = ['mode', 'dim', 'eps']
def __init__(self, mode='global', dim=2, eps=1e-10):
super(CMVN, self).__init__()
if (mode != 'global'):
raise NotImplementedError('Only support global mean variance normalization.')
self.mode = mode
sel... |
class FeatureExtractor(nn.Module):
'Feature extractor, transforming file path to Mel spectrogram'
def __init__(self, mode='fbank', num_mel_bins=80, decode_wav=False, apply_cmvn=True, **kwargs):
super(FeatureExtractor, self).__init__()
assert (mode == 'fbank'), 'Only Mel-spectrogram implemente... |
def create_transform(audio_config):
feat_type = audio_config.pop('feat_type')
feat_dim = audio_config.pop('feat_dim')
decode_wav = audio_config.pop('decode_wav', False)
apply_cmvn = audio_config.pop('cmvn', True)
transforms = FeatureExtractor(feat_type, feat_dim, decode_wav, apply_cmvn, **audio_co... |
class UpstreamExpert(UpstreamBase):
def __init__(self, ckpt, **kwargs):
super().__init__(**kwargs)
ckpt = torch.load(ckpt, map_location='cpu')
config = ckpt['config']
(self.preprocessor, feat_dim) = create_transform(config['data']['audio'])
self.model = APC(feat_dim, **con... |
def apc_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 apc_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from URL\n ckpt (str): URL\n '
return apc_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
|
def apc(refresh=False, *args, **kwargs):
'\n The default model\n refresh (bool): whether to download ckpt/config again if existed\n '
return apc_360hr(*args, refresh=refresh, **kwargs)
|
def apc_360hr(refresh=False, *args, **kwargs):
'\n The apc standard model on 360hr\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/leo19941227/apc_series/resolve/main/apc_360hr.ckpt'
return apc_url(*args, refresh=refresh, **kwarg... |
def apc_960hr(refresh=False, *args, **kwargs):
'\n The apc standard model on 960hr\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/leo19941227/apc_series/resolve/main/apc_960hr.ckpt'
return apc_url(*args, refresh=refresh, **kwarg... |
class VQLayer(nn.Module):
def __init__(self, input_size, codebook_size, code_dim, gumbel_temperature):
'\n Defines a VQ layer that follows an RNN layer.\n input_size: an int indicating the pre-quantized input feature size,\n usually the hidden size of RNN.\n codebook_size:... |
def ast(refresh: bool=False, window_secs: float=10.24, stride_secs: float=10.24, **kwds):
kwds['ckpt'] = _urls_to_filepaths('https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1', refresh=refresh)
return _UpstreamExpert(window_secs=window_secs, stride_secs=stride_secs, **kwds)
|
def audio_albert_local(ckpt, *args, **kwargs):
'\n The model from local ckpt\n ckpt (str): PATH\n feature_selection (int): -1 (default, the last layer) or an int in range(0, max_layer_num)\n '
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def audio_albert_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from URL\n ckpt (str): URL\n '
return audio_albert_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
|
def audio_albert(refresh=False, *args, **kwargs):
'\n The default model\n refresh (bool): whether to download ckpt/config again if existed\n '
return audio_albert_960hr(*args, refresh=refresh, **kwargs)
|
def audio_albert_960hr(refresh=False, *args, **kwargs):
'\n The audio albert base model on 960hr\n refresh (bool): whether to download ckpt/config again if existed\n '
return audio_albert_logMelBase_T_share_AdamW_b32_1m_960hr_drop1(*args, refresh=refresh, **kwargs)
|
def audio_albert_logMelBase_T_share_AdamW_b32_1m_960hr_drop1(refresh=False, *args, **kwargs):
'\n Feature: 80-dim log Mel\n Alteration: time\n Optimizer: AdamW\n Batch size: 32\n Total steps: 1M\n Unlabled Speech: 960hr\n '
kwargs['ckpt'] = 'https://huggingface.co/s3prl/audio_albert/resol... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.